2017-09-23 104 views
0

我想反序列化JSON的一些字符串这样的: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库。

谢谢

回答

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

    } 
+0

是的,它解决了我的问题。非常感谢你 – hkhk

+0

不客气:) – uyquoc

0

thisextendsthat的答案是罚款您的具体情况。不过,也有完全动态的选项反序列化:

1)解析成JToken

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

2)解析成dynamic

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

我尝试了动态版本,这也可以,谢谢。还有一个问题:我如何从一个子对象中获得'书'?关键(AAA,AAX)可以是任何,我不知道哪一个出现在响应中 – hkhk