【问题标题】:Parse JSON string with inconsistent field names解析具有不一致字段名称的 JSON 字符串
【发布时间】:2015-09-28 14:12:18
【问题描述】:

我在反序列化以下 JSON 结构时遇到问题。每个节点都包含一个 ID 和带有值的多语言代码。语言属性的数量不一致。但我需要将这些值作为具有 Language 字段和 Value 字段的对象列表。

       [{  
          "id":"w_312457",
          "eng":"deep-fat frying",
          "ger":"Frittieren"
       },
       {  
          "id":"w_312458",
          "fre":"frying",
          "ger":"braten (in Öl)"
       },
       {  
          "id":"w_312477",
          "ger":"perfekt gewürzte und abgestimmte Soße "
      }]

我尝试使用 JsonPropertyName 属性并获得了 ID 值。但是对于 lang 节点,我不知道我可以指定什么名称。以下是我的 CLR 对象,

 public class Word
 {
    public string Id { get; set; } // This is working

    // What can I specify here. I need a list of objects each with a lang code and value.
 }

【问题讨论】:

  • 您有没有通过任何方法取得进展?听起来你想要一个List<Dictionary<string,string>>,然后再解析字典。
  • 我很想稍微改变一下 JSON 的结构。所以定义可以在任何数组中:"id": "w_313223", "translations": [ { "lang": "ger", "value": "perfekt gewürzte und abgestimmte Soße" } ] 你明白我的意思吗?这样数组就可以有x 的翻译量

标签: c# json deserialization


【解决方案1】:

方法一:

一种方法是简单地添加所有值并检查它们是否存在。例如,这是包含所有语言值的类:

public class Word
{
    public string id { get; set; }
    public string eng { get; set; }
    public string ger { get; set; }
    public string fre { get; set; }
}

你会得到这样的列表:

var words  = JsonConvert.DeserializeObject<List<Word>>(json);

当然,这是假设只有 3 种语言,并且不会添加更多语言(这永远不会发生!)

方法二:

this线程所示,可以像这样反序列化成字典对象列表:

var words = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json);

您可以像这样访问所有键和值:

foreach (var word in words)
{
    foreach (var key in word.Keys)
    {
        Console.WriteLine($"value for the key {key} is {word[key]}");
    }
}

这将产生以下结果:

键 ID 的值为 w_312457

键 eng 的值是油炸

key ger 的值是 Frittieren

键 ID 的值为 w_312458

键 fre 的值正在煎炸

密钥 ger 的值是 braten(在 Öl 中)

键 ID 的值为 w_312477

密钥 ger 的值是 perfekt gewürzte und abgestimmte Soße

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    相关资源
    最近更新 更多