2012-06-21 10 views
27

Używam JSON.NET w C# do analizy odpowiedzi z API Klout. Moja odpowiedź jest następująca:Iterowanie przez obiekt JSON w C#

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

Jak widać, zawiera 5id znaczników. Może następnym razem będzie to 6 lub 1 lub jakaś inna liczba. Chcę iterować nad JSON i uzyskać wartość każdego tagu id. Nie mogę uruchomić pętli, nie wiedząc, ile ich będzie. Jak mogę to rozwiązać?

Odpowiedz

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); 
} 

lub

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; 
} 
+0

Mówi brakuje odniesienia do Micrsofot.CSHARp i System.Core.I dodaje odniesienia do both.It za APS.NET App –

+2

Niestety „dynamiczne” słowo kluczowe jest dostępny od ram 4,0 roku :( –

15

Można użyć JsonTextReader do zapoznania się z JSON i iteracyjne nad tokeny:

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

chociaż nie jest wymogiem, jest to jedyna odpowiedź, która pozwala na iterację poprzez JObject bez znajomości struktury wcześniej. –

+1

To jest bardzo dobra odpowiedź, daje możliwość uzyskania pełnej kontroli nad analizowanym JSON. Bardzo przydatne, dziękuję! – Zoran

0

ten pracował dla mnie, konwertuje do zagnieżdżonego JSON do czytelny 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; 

    } 

Wykorzystanie

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