2012-06-21 4 views
27

나는 C#에서 JSON.NET을 사용하여 Klout API의 응답을 구문 분석한다. 내 응답은 다음과 같습니다.C#에서 JSON 객체 반복하기

[ 
    { 
    "id": "5241585099662481339", 
    "displayName": "Music", 
    "name": "music", 
    "slug": "music", 
    "imageUrl": "http://kcdn3.klout.com/static/images/music-1333561300502.png" 
    }, 
    { 
    "id": "6953585193220490118", 
    "displayName": "Celebrities", 
    "name": "celebrities", 
    "slug": "celebrities", 
    "imageUrl": "http://kcdn3.klout.com/static/images/topics/celebrities_b32741b6703151cc7bd85fba24c44c52.png" 
    }, 
    { 
    "id": "5757029936226020304", 
    "displayName": "Entertainment", 
    "name": "entertainment", 
    "slug": "entertainment", 
    "imageUrl": "http://kcdn3.klout.com/static/images/topics/Entertainment_7002e5d2316e85a2ff004fafa017ff44.png" 
    }, 
    { 
    "id": "3718", 
    "displayName": "Saturday Night Live", 
    "name": "saturday night live", 
    "slug": "saturday-night-live", 
    "imageUrl": "http://kcdn3.klout.com/static/images/icons/generic-topic.png" 
    }, 
    { 
    "id": "8113008320053776960", 
    "displayName": "Hollywood", 
    "name": "hollywood", 
    "slug": "hollywood", 
    "imageUrl": "http://kcdn3.klout.com/static/images/topics/hollywood_9eccd1f7f83f067cb9aa2b491cd461f3.png" 
    } 
] 

위의 내용과 마찬가지로 5 id 태그가 포함되어 있습니다. 아마도 다음에 6이나 1 또는 다른 숫자가 될 것입니다. JSON을 반복하고 각 id 태그의 값을 얻고 싶습니다. 내가 얼마나 많이 있을지 모른 채 루프를 돌릴 수는 없다. 이 문제를 어떻게 해결할 수 있습니까?

답변

55
dynamic dynJson = JsonConvert.DeserializeObject(json); 
foreach (var item in dynJson) 
{ 
    Console.WriteLine("{0} {1} {2} {3}\n", item.id, item.displayName, 
     item.slug, item.imageUrl); 
} 

또는

당신은 JSON을 읽고 토큰을 반복하는 JsonTextReader을 사용할 수 있습니다
+0

이 Micrsofot.CSHARp 및 System.Core.I both.It의 APS.NET 앱 –

+2

에 추가 참조에 빠진 참조가 불행하게도 '동적'키워드는 이후 프레임 워크 4.0 :( –

15

var list = JsonConvert.DeserializeObject<List<MyItem>>(json); 

public class MyItem 
{ 
    public string id; 
    public string displayName; 
    public string name; 
    public string slug; 
    public string imageUrl; 
} 
:

using (var reader = new JsonTextReader(new StringReader(jsonText))) 
{ 
    while (reader.Read()) 
    { 
     Console.WriteLine("{0} - {1} - {2}", 
          reader.TokenType, reader.ValueType, reader.Value); 
    } 
} 
+2

그것은 비록에서 사용할 수 있습니다 말한다 요구 사항은 아니며,이 구조체를 미리 알지 못해 JObject를 반복 할 수있는 유일한 대답입니다. –

+1

이것은 매우 좋은 대답으로, 구문 분석 된 JSON을 완전히 제어 할 수있는 옵션을 제공합니다. 매우 유용합니다. 감사합니다! – Zoran

0

이 나를 위해 일하기 쉬운에 중첩 된 JSON으로 변환 읽을 YAML

string JSONDeserialized {get; set;} 
    public int indentLevel; 

    private bool JSONDictionarytoYAML(Dictionary<string, object> dict) 
    { 
     bool bSuccess = false; 
     indentLevel++; 

     foreach (string strKey in dict.Keys) 
     { 
      string strOutput = "".PadLeft(indentLevel * 3) + strKey + ":"; 
      JSONDeserialized+="\r\n" + strOutput; 

      object o = dict[strKey]; 
      if (o is Dictionary<string, object>) 
      { 
       JSONDictionarytoYAML((Dictionary<string, object>)o); 
      } 
      else if (o is ArrayList) 
      { 
       foreach (object oChild in ((ArrayList)o)) 
       { 
        if (oChild is string) 
        { 
         strOutput = ((string)oChild); 
         JSONDeserialized += strOutput + ","; 
        } 
        else if (oChild is Dictionary<string, object>) 
        { 
         JSONDictionarytoYAML((Dictionary<string, object>)oChild); 
         JSONDeserialized += "\r\n"; 
        } 
       } 
      } 
      else 
      { 
       strOutput = o.ToString(); 
       JSONDeserialized += strOutput; 
      } 
     } 

     indentLevel--; 

     return bSuccess; 

    } 

사용

 Dictionary<string, object> JSONDic = new Dictionary<string, object>(); 
     JavaScriptSerializer js = new JavaScriptSerializer(); 

      try { 

      JSONDic = js.Deserialize<Dictionary<string, object>>(inString); 
      JSONDeserialized = ""; 

      indentLevel = 0; 
      DisplayDictionary(JSONDic); 

      return JSONDeserialized; 

     } 
     catch (Exception) 
     { 
      return "Could not parse input JSON string"; 
     }