【问题标题】:Deserialize json into multiple classes with System.Text.Json使用 System.Text.Json 将 json 反序列化为多个类
【发布时间】:2021-07-18 01:12:56
【问题描述】:

我有一个来自视频游戏的 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; }
}

【问题讨论】:

    标签: c# json deserialization system.text.json


    【解决方案1】:

    您的 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 架构,那么您需要更改的代码就会少得多以保持您的代码正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 2020-03-24
      • 2021-12-08
      • 2020-04-06
      • 2020-10-24
      相关资源
      最近更新 更多