很长对象的嵌套反序列化-从Json到C#
我想将以下字符串对象(JSON字符串)反序列化为C#List。 请注意,这是JSON格式的,不包含C#转义字符等很长对象的嵌套反序列化-从Json到C#,c#,json-deserialization,C#,Json Deserialization,我想将以下字符串对象(JSON字符串)反序列化为C#List。 请注意,这是JSON格式的,不包含C#转义字符等 { "2020-01-01": { "price" : 100 }, "2020-01-02": { "price" : 101 }, "2020-01-03": { "price" : 103 },
{
"2020-01-01":
{
"price" : 100
},
"2020-01-02":
{
"price" : 101
},
"2020-01-03":
{
"price" : 103
},
"2020-01-04":
{
"price" : 104
},
...
}
预期结果将是一个对象列表,如:
class DataPoint
{
public string Date { get; set;}
public int Price { get; set;}
}
例如,结果应该是这样的
{{"2020-01-01", 100},
{"2020-01-02", 101},
{"2020-01-03", 103},
{"2020-01-04", 104}}
请注意,这个解决方案对我来说是不可接受的,因为日期可能很多,而且不可能像这里建议的那样编写一个涵盖所有数据点的类
您能建议一种方法将原始字符串JSON对象反序列化为C#collection的列表类型吗?创建如下类:
public class Price
{
public int price { get; set; }
}
var results = JsonConvert.DeserializeObject<Dictionary<string, Price>>(data);
var items = new List<DataPoint>();
foreach (var item in results)
{
items.Add(new DataPoint {Date = item.Key, Price = item.Value.price});
}
然后将JSON反序列化到字典中,如下所示:
public class Price
{
public int price { get; set; }
}
var results = JsonConvert.DeserializeObject<Dictionary<string, Price>>(data);
var items = new List<DataPoint>();
foreach (var item in results)
{
items.Add(new DataPoint {Date = item.Key, Price = item.Value.price});
}
或者,如果您喜欢大而长的LINQ表达式:
var items = results.Select(item => new DataPoint {Date = item.Key, Price = item.Value.price}).ToList();
这将为您提供您要查找的列表。它只是一个对象字典,该对象有一个属性(Price),我尝试了您的建议,如果我们在对象周围使用“[]”(但是在最初的示例中,它是一个带有“{}”的对象),我会收到以下错误消息“无法反序列化当前JSON数组(例如:。[1,2,3])转换为类型“Dictionary”,因为该类型需要一个JSON对象(例如{“name”:“value”})要正确反序列化。@ZoltanHalasz如果您的json与您在帖子中发布的完全相同,那么Flydog57的回答应该是100%正确的。这证明了这一点:是的,它是正确的,我的json对象代码中几乎没有空格或格式问题。