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 に答える