迭代c#中的json元素

时间:2013-09-02 13:34:10

标签: c# json dynamic

我从服务中返回了以下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#中创建一个列表中的“suggestion”元素。什么是最好的方式?
  2. 没有被“”包围的元素是什么。不应该所有json元素都被“”包围吗? 感谢。
  3. 修改: 这是基于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()));
                    }
    
     }
    

1 个答案:

答案 0 :(得分:1)

json字符串问题:

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

    这应该有效:

           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"
        ]
      }
    }