【问题标题】:JSON deserialize subclassesJSON反序列化子类
【发布时间】:2017-09-23 16:05:30
【问题描述】:

我想像这样反序列化一些 JSON 字符串:

    {"time":1506174868,"pairs":{
    "AAA":{"books":8,"min":0.1,"max":1.0,"fee":0.01},
    "AAX":{"books":8,"min":0.1,"max":1.0,"fee":0.01},
    "AQA":{"books":8,"min":0.1,"max":1.0,"fee":0.01}
    }}

其中 AAA、AAX、...有数百种变化

我将此 Json 作为类粘贴到 VS2017 中并得到以下内容:

public class Rootobject
{
    public int time { get; set; }
    public Pairs pairs { get; set; }
}

public class Pairs
{
    public AAA AAA { get; set; }
    public AAX AAX { get; set; }
    public AQA AQA { get; set; }
}

public class AAA
{
    public int books { get; set; }
    public float min { get; set; }
    public float max { get; set; }
    public float fee { get; set; }
}

public class AAX
{
    public int books { get; set; }
    public float min { get; set; }
    public float max { get; set; }
    public float fee { get; set; }
}

public class AQA
{
    public int books { get; set; }
    public float min { get; set; }
    public float max { get; set; }
    public float fee { get; set; }
}

我会尽量避免数百个类声明,因为所有类都是相同的,除了 他们的名字。

我尝试将其序列化为数组或列表,但由于这不是数组而出现异常。

我使用 Newtonsoft JSON 库。

谢谢

【问题讨论】:

    标签: c# json json-deserialization


    【解决方案1】:

    当然,您可以将json字符串解析为对象,如下所示:

        public class Rootobject
    {
        public int time { get; set; }
        public Dictionary<string, ChildObject> pairs { get; set; }
    }
    
    public class ChildObject
    {
    
        public int books { get; set; }
        public float min { get; set; }
        public float max { get; set; }
        public float fee { get; set; }
    }
    
    class Program
    {
        static string json = @"
            {""time"":1506174868,""pairs"":{
            ""AAA"":{""books"":8,""min"":0.1,""max"":1.0,""fee"":0.01},
            ""AAX"":{""books"":8,""min"":0.1,""max"":1.0,""fee"":0.01},
            ""AQA"":{""books"":8,""min"":0.1,""max"":1.0,""fee"":0.01}
            }
        }";
    
        static void Main(string[] args)
        {
            Rootobject root = JsonConvert.DeserializeObject<Rootobject>(json);
            foreach(var child in root.pairs)
            {
                Console.WriteLine(string.Format("Key: {0}, books:{1},min:{2},max:{3},fee:{4}", 
                    child.Key, child.Value.books, child.Value.max, child.Value.min, child.Value.fee));
            }
    
        }
    

    【讨论】:

      【解决方案2】:

      thisextendsthat 的回答适合您的具体情况。但是,反序列化有完全动态的选项:

      1) 解析成JToken

      var root = JObject.Parse(jsonString);
      var time = root["time"];
      

      2) 解析成dynamic

      dynamic d = JObject.Parse(jsonString);
      var time = d.time;
      

      【讨论】:

      • 我试过动态版,也可以,谢谢。还有一个问题:如何从子对象中获取“书籍”?密钥(AAA,AAX)可以是任意的,我不知道响应中存在哪一个
      猜你喜欢
      • 2013-12-15
      • 1970-01-01
      • 2015-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多