use*_*459 4 c# serialization json json.net
请帮我.我在哪里缺少信息?我需要反序列化以下JSON字符串.
{ "结果":[{ "系列":[{ "Name": "PWR_00000555", "列": "时间", "最后一个"], "值":["1970-01-01T00:00: 00Z",72]]}]}]}
为此,我定义了我的课程:
public class Serie
{
public Serie()
{
this.Points = new List<object[]>();
}
[JsonProperty(PropertyName = "results")]
public string results { get; set; }
[JsonProperty(PropertyName = "series")]
public string sries { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "columns")]
public string[] ColumnNames { get; set; }
[JsonProperty(PropertyName = "values")]
public List<object[]> Points { get; set; }
Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用反序列化器时,它会给出一个例外.
{"无法将当前JSON对象(例如{\"name \":\"value \"})反序列化为类型'System.Collections.Generic.List`1 [InfluxDB.Serie]',因为该类型需要JSON数组(例如[1,2,3])要正确反序列化.\ r \n要修复此错误要么将JSON更改为JSON数组(例如[1,2,3]),要么更改反序列化类型以使其正常.可以从JSON对象反序列化的.NET类型(例如,不是像整数这样的基本类型,不是像数组或List <T>这样的集合类型).JsonObjectAttribute也可以添加到类型中以强制它从JSON对象反序列化.\ r \n路径'结果',第2行,第12位."}
Bri*_*ers 14
您收到此错误是因为您的JSON是分层的,而您的类基本上是平的.如果您使用JSONLint.com来验证和重新格式化JSON,您可以更好地查看结构:
{
"results": [
{
"series": [
{
"name": "PWR_00000555",
"columns": [
"time",
"last"
],
"values": [
[
"1970-01-01T00:00:00Z",
72
]
]
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
这对应于以下类结构(我最初使用json2csharp.com生成,然后手动编辑以添加[JsonProperty]属性):
public class RootObject
{
[JsonProperty("results")]
public List<Result> Results { get; set; }
}
public class Result
{
[JsonProperty("series")]
public List<Series> Series { get; set; }
}
public class Series
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("columns")]
public List<string> ColumnNames { get; set; }
[JsonProperty("values")]
public List<List<object>> Points { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
您可以将JSON反序列化为上述类结构,如下所示:
var root = JsonConvert.DeserializeObject<RootObject>(jsonString);
Run Code Online (Sandbox Code Playgroud)
小提琴:https://dotnetfiddle.net/50Z64s
如果您愿意牺牲 IntelliSense 和编译时类型安全,那么您可以简单地将 JSON 反序列化为动态对象:
dynamic parsed = JsonConvert.DeserializeObject(jsonString);
PrintAllNames(parsed);
//...
private void PrintAllNames(dynamic obj)
{
foreach(var result in obj.results)
foreach(var item in result.series)
Console.WriteLine(item.name);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30627 次 |
| 最近记录: |