0

我从服务返回了以下 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()));
                }

 }
4

1 回答 1

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"
    ]
  }
}
于 2013-09-02T14:00:38.853 回答