JSON到C# – 在json中列出没有子字段名称的字段?

使用Json.net(Newtonsoft.json),我如何定义一个C#类(或类)来处理下面的json?

“数据”字段似乎是级别/描述子字段的列表,但请注意它们之前没有字段名称。

“错误”字段似乎是错误编号/错误消息子字段的列表,但请注意,它们也不以字段名称开头。

{ "status": "error", "data": [ { "warning" : "your input was wrong" } ], "error": [ { "373": "Error description goes here" } ] } 

此类定义不会生成解析错误; 但是数据和错误的内容不正确。

 public class ApiResponse { [JsonProperty(PropertyName = "status")] public string Status; [JsonProperty(PropertyName = "data")] public IEnumerable<KeyValuePair> Data; [JsonProperty(PropertyName = "error")] public IEnumerable<KeyValuePair> Errors; }; // this doesn't throw a parsing exception, but the resulting // Data and Errors fields are not correctly populated. var x = JsonConvert.DeserializeObject(SampleJson); 

任何帮助将不胜感激,谢谢。

尝试将您的DataErrors成员定义为词典的IEnumerables而不是KeyValuePairs的IEnumerables。 (Json.Net期望KeyValuePairs在JSON中表示为具有显式KeyValue属性的对象,这不是您拥有的那些。)

 public class ApiResponse { [JsonProperty(PropertyName = "status")] public string Status; [JsonProperty(PropertyName = "data")] public IEnumerable> Data; [JsonProperty(PropertyName = "error")] public IEnumerable> Errors; }; 

然后,您可以使用带有SelectManyforeach循环读取数据:

 var x = JsonConvert.DeserializeObject(SampleJson); foreach (var kvp in x.Data.SelectMany(d => d)) { Console.WriteLine(kvp.Key + ": " + kvp.Value); } foreach (var kvp in x.Errors.SelectMany(d => d)) { Console.WriteLine(kvp.Key + ": " + kvp.Value); } 

小提琴: https : //dotnetfiddle.net/KJuAPu

您创建的课程几乎没有问题。 根据提供的JSON,您应该创建类似于以下代码的类。

  public class Data { [JsonProperty(PropertyName = "warning")] public string Warning { get; set; } } public class Error { [JsonProperty(PropertyName = "373")] public string Col_373 { get; set; } } public class ApiResponse { [JsonProperty(PropertyName = "status")] public string Status { get; set; } [JsonProperty(PropertyName = "data")] public List Data { get; set; } [JsonProperty(PropertyName = "error")] public List Error { get; set; } } 

一旦你设计了这样的结构,你总是可以将它恢复到你的对象结构,如下面的代码片段。 看起来,你对属性名称和值感到困惑。

  string json = "{\"status\":\"error\", \"data\": [{\"warning\" : \"your input was wrong\" }], \"error\": [{\"373\": \"Error description goes here\"}]}"; var res = JsonConvert.DeserializeObject(json); 

再观察一次。

“373” :“错误描述在这里”

请不要使用数字作为键/列名称。