您的 JSON 架构与您的课程不直接匹配。您最好创建旨在简化反序列化的类,然后使用 Adapter Pattern 创建满足您使用 c# json 版本需求的类。
public class OnlineKillsSource
{
[JsonPropertyName("onlinepvp_kills:all")]
public int PVP { get; set; }
[JsonPropertyName("onlinepve_kills:all")]
public int PVE { get; set; }
}
然后使用带有构造函数的适配器模式:
public class Online
{
public (OnlineKillsSource source)
{
PVP = new PVP { Kills = source.PVP };
PVE = new PVE { Kills = source.PVE };
}
public PVP PVP { get; set; }
public PVE PVE { get; set; }
}
public class PVP
{
public int Kills { get; set; }
}
public class PVE
{
public int Kills { get; set; }
}
用法:
JsonSerializer.Deserialize<OnlineKillsSource>(jsonString);
var online = new Online(OnlineKillSource);
现在的优势是您Separate the Concerns反序列化外部数据并将数据转换为标准消耗品。
如果您的数据源更改了 JSON 架构,您需要更改的代码就会少得多,以确保您的代码正常工作。
本文链接:https://www.f2er.com/78597.html