C# JSON反序列化子类
我想反序列化一些JSON字符串,如下所示:C# JSON反序列化子类,c#,json,json-deserialization,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。。。有数百种变体 我将此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; }
}
我会尽量避免数百个类声明,因为除了
他们的名字
我试图将其序列化为数组或列表,但由于这不是数组,所以出现异常
我使用newtonsoftjson库
谢谢当然,您可以将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));
}
}
公共类根对象
{
公共整数时间{get;set;}
公共字典对{get;set;}
}
公共类子对象
{
公共整数书籍{get;set;}
公共浮点最小值{get;set;}
公共浮点最大值{get;set;}
公共浮动费用{get;set;}
}
班级计划
{
静态字符串json=@”
{“时间”:1506174868,“成对”:{
“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}
}
}";
静态void Main(字符串[]参数)
{
Rootobject root=JsonConvert.DeserializeObject(json);
foreach(root.pairs中的var子级)
{
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) 解析为JToken
var root = JObject.Parse(jsonString);
var time = root["time"];
2) 解析为动态
dynamic d = JObject.Parse(jsonString);
var time = d.time;
我尝试了动态版本,这也很有效,谢谢。还有一个问题:如何从子对象获取“书籍”?密钥(AAA,AAX)可以是任意的,我不知道响应中出现了哪一个