【问题标题】:iterating json elements in c# [duplicate]在c#中迭代json元素[重复]
【发布时间】:2013-09-03 21:20:21
【问题描述】:

我从服务中返回了以下 json:

{
   responseHeader: {
      status: 0,
      QTime: 1
   },
   spellcheck: {
     suggestions: [
       "at",
       {
            numFound: 2,
            startOffset: 0,
            endOffset: 2,
            suggestion: [
               "at least five tons of glitter alone had gone into it before them and",
                "at them the designer of the gun had clearly not been instructed to beat"
            ]
       },
       "collation",
       "(at least five tons of glitter alone had gone into it before them and)"
    ]
  }
}
  1. 我需要在 C# 中创建“建议”元素内的内容列表。最好的方法是什么?
  2. 什么是没有被“”包围的元素。不应该所有的json元素都被“”包围吗? 谢谢。

编辑: 这是基于 dcastro 的回答

 dynamic resultChildren = result.spellcheck.suggestions.Children();
 foreach (dynamic child in resultChildren)
 {
       var suggestionObj = child as JObject;
                if (suggestionObj != null)
                {
                    var subArr = suggestionObj.Value<JArray>("suggestion");
                    strings.AddRange(subArr.Select(suggestion =>               suggestion.ToString()));
                }

 }

【问题讨论】:

    标签: c# json dynamic


    【解决方案1】:

    你的 json 字符串有问题:

    1. 是的,所有键都应该用双引号括起来
    2. 您的“建议”结构没有任何意义...您不应该有一组定义明确的“建议”对象吗?现在,您有一个混合了字符串(“at”、“collat​​ion”)和其他 json 对象(带有 numFound 的对象等)的数组。
    3. 在那里有一个字符串“at”的目的是什么?这不是一个 json 键,它只是一个字符串......

    编辑

    这应该可行:

           JObject obj = JObject.Parse(json);
           var suggestionsArr = obj["spellcheck"].Value<JArray>("suggestions");
    
           var strings = new List<string>();
    
           foreach (var suggestionElem in suggestionsArr)
           {
               var suggestionObj = suggestionElem as JObject;
               if (suggestionObj != null)
               {
                   var subArr = suggestionObj.Value<JArray>("suggestion");
                   strings.AddRange(subArr.Select(suggestion => suggestion.ToString()));
               }
           }
    

    假设以下json字符串:

    {
       "responseHeader": {
          "status": 0,
          "QTime": 1
       },
       "spellcheck": {
         "suggestions": [
            "at",
            {
                "numFound": 2,
                "startOffset": 0,
                "endOffset": 2,
                "suggestion": ["at least five tons of glitter alone had gone into it before them and", "at them the designer of the gun had clearly not been instructed to beat"]
            },
            "collation"
        ]
      }
    }
    

    【讨论】:

    • 这看起来像 SOLR 响应 - 所以除了属性名称/键实际上应该被引用的事实之外是正确的 - 实际上 - 建议通常有更多数据 - 就像在你的对象数组中一样重新正确
    • 正确。我要问的是如何解析 SOLR 答案的建议。
    • 我已经编辑了我的答案
    • 太棒了。我做了一些改进,我会将其添加到问题中。
    猜你喜欢
    • 1970-01-01
    • 2012-09-15
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 2018-12-29
    • 1970-01-01
    相关资源
    最近更新 更多