JSON 反序列化子类

JSON deserialize subclasses

我想像这样反序列化一些 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 ……有数百种变体

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

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; }
}

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

我试图将其序列化为数组或列表,但出现异常,因为这不是数组。

我使用 Newtonsoft JSON 库。

谢谢

当然,您可以将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));
        }

    }

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

1) 解析为 JToken

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

2) 解析成 dynamic

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