超长对象的嵌套反序列化——从 Json 到 C#
Nested Deserialization of a Very Long Object - From Json to C#
我想将以下字符串对象 (JSON 字符串) 反序列化为 C# 列表。
请注意这是 JSON 格式,而不是 C# 转义字符等
{
"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}}
请注意,https://json2csharp.com/ 解决方案对我来说是不可接受的,因为日期可能很多,而且不可能像那里建议的那样编写涵盖所有数据点的 class。
能否请您提供一种将原始字符串 JSON 对象反序列化为 C# 集合的 List 类型的方法?
像这样创建一个class:
public class Price
{
public int price { get; set; }
}
然后将您的 JSON 反序列化为 Dictionary<string, Price>
,如下所示:
var results = JsonConvert.DeserializeObject<Dictionary<string, Price>>(data);
在字典中找到它后,您可以像这样构建 DataPoint
class 项目的集合:
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();
这将为您提供所需的列表。
我想将以下字符串对象 (JSON 字符串) 反序列化为 C# 列表。 请注意这是 JSON 格式,而不是 C# 转义字符等
{
"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}}
请注意,https://json2csharp.com/ 解决方案对我来说是不可接受的,因为日期可能很多,而且不可能像那里建议的那样编写涵盖所有数据点的 class。
能否请您提供一种将原始字符串 JSON 对象反序列化为 C# 集合的 List 类型的方法?
像这样创建一个class:
public class Price
{
public int price { get; set; }
}
然后将您的 JSON 反序列化为 Dictionary<string, Price>
,如下所示:
var results = JsonConvert.DeserializeObject<Dictionary<string, Price>>(data);
在字典中找到它后,您可以像这样构建 DataPoint
class 项目的集合:
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();
这将为您提供所需的列表。