使用 System.Text.Json 将 json 反序列化为多个类

我有一个来自视频游戏的 json,在根级别有大约 1000 个值并使用蛇形大小写键,我如何使用 System.Json.Text 将其反序列化为多个类?谢谢

例如

{
    "onlinepvp_kills:all": 0,"onlinepve_kills:all": 0
}

public class Online
{
    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; }
}
cecilia53520 回答:使用 System.Text.Json 将 json 反序列化为多个类

您的 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

大家都在问