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

标签 c# json json.net deserialization

使用 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<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);

如有任何帮助,我们将不胜感激。

最佳答案

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

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;
};

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

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);
}

fiddle :https://dotnetfiddle.net/KJuAPu

关于c# - JSON 到 C#——在 json 中列出没有子字段名称的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37837977/

相关文章:

.net - 复杂消息和大众运输反序列化

c# - Nhibernate 查询超时而 sql 查询没有

c# - 存储:C# 等同于 PowerShell 命令

c# - 为您的 C# 应用程序创建安装程序时使用的数据库

json - Swift 到 Swift 3 代码转换 : Reading JSON files

c# - 使用流通过 Json.NET 创建 BSON 字节数组(文件格式)

c# - 我如何从最后循环遍历列表?

javascript - 加载位于根目录之外的 json 和图像

javascript - 如何在 JavaScript 字符串中替换\with\\

c# - 是否有任何约定或内置概念如何注入(inject) Json 序列化程序?