JSON反序列化子类

时间:2017-09-23 16:05:30

标签: c# json json-deserialization

我想像这样反序列化一些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粘贴为类,并获得以下内容:

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 lib。

谢谢

2 个答案:

答案 0 :(得分:1)

当然,您可以按如下方式将json字符串解析为object:

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

    }

答案 1 :(得分:0)

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

1)解析为JToken

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

2)解析为dynamic

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