JSON到C#-列出JSON中没有子字段名称的字段? [英] JSON to C# -- list fields without sub-field names in json?
问题描述
使用Json.net(Newtonsoft.json),如何定义一个C#类(或多个类)来处理下面的json?
Using Json.net (Newtonsoft.json), how can I define a C# class (or classes) to handle the json below?
数据"字段似乎是级别/描述子字段的列表,但请注意,它们不以字段名开头.
The 'data' field appears to be a list of level/description sub-fields but note they are not preceded by field names.
错误"字段似乎是错误编号/错误消息子字段的列表,但请注意,它们也不以字段名开头.
The 'error' field appears to be a list of error-number/error-message sub-fields but note, they too, are not preceded by field names.
{
"status": "error",
"data": [
{
"warning" : "your input was wrong"
}
],
"error": [
{
"373": "Error description goes here"
}
]
}
该类定义不会产生解析错误;但是数据和错误"的内容不正确.
This class definition does not generate parsing errors; however the contents of Data and Errors is not correct.
public class ApiResponse
{
[JsonProperty(PropertyName = "status")]
public string Status;
[JsonProperty(PropertyName = "data")]
public IEnumerable<KeyValuePair<string, string>> Data;
[JsonProperty(PropertyName = "error")]
public IEnumerable<KeyValuePair<int, string>> Errors;
};
// this doesn't throw a parsing exception, but the resulting
// Data and Errors fields are not correctly populated.
var x = JsonConvert.DeserializeObject<ApiResponse>(SampleJson);
感谢您的任何帮助.
推荐答案
尝试将您的Data
和Errors
成员定义为Dictionary的IEnumerables,而不是KeyValuePairs的IEnumerables. (Json.Net期望KeyValuePairs在JSON中表示为具有显式Key
和Value
属性的对象,而这不是您所拥有的.)
Try defining your Data
and Errors
members as IEnumerables of Dictionaries rather than IEnumerables of KeyValuePairs. (Json.Net expects KeyValuePairs to be represented in JSON as objects with explicit Key
and Value
properties, which is not what you have there.)
public class ApiResponse
{
[JsonProperty(PropertyName = "status")]
public string Status;
[JsonProperty(PropertyName = "data")]
public IEnumerable<Dictionary<string, string>> Data;
[JsonProperty(PropertyName = "error")]
public IEnumerable<Dictionary<int, string>> Errors;
};
然后可以使用SelectMany
和SelectMany
循环使用foreach
循环读取数据:
You can then read the data out using a foreach
loop with SelectMany
:
var x = JsonConvert.DeserializeObject<ApiResponse>(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到C#-列出JSON中没有子字段名称的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!