2012-01-23 14 views
5

Ho una struttura JSON che vorrei analizzare manualmente ad un oggetto POCO usando JSON.NET.Come posso scorrere i dizionari nidificati con JSON.NET?

La struttura JSON è un gruppo di dizionari nidificati ... Il dizionario radice contiene categorie, il livello successivo contiene prodotti all'interno di tali categorie e l'ultimo livello contiene versioni di tali prodotti.

{ 
     "category-1": { 
      "product-1": { 
       "product-version-1": { 
        "id":1, 
        ... 
       } 
      } 
     }, 
     "category-2": { 
      "product-2": { 
       "product-version-2": { 
        "id":2, 
        ... 
       } 
      }, 
      "product-3": { 
       "product-version-3": { 
        "id":3, 
        ... 
       } 
      } 
     } 
} 

vorrei analizzare questa struttura, tenendo presente le chiavi di tutti i dizionari non sono noti a me prima del tempo.

Questo era il codice che avevo scritto (stavo per convertire in LINQ una volta funzionato ...) - Mi aspettavo che questo funzionasse con un paio di cicli annidati ma chiaramente JTokens e JObjects non funzionano come Pensavo ... L'ID è sempre nullo.

var productsJObject = JObject.Parse(result.Content.ReadAsStringAsync().Result); 

foreach (var category in productsJObject) 
{ 
    foreach (var product in category.Value) 
    { 
     foreach (var version in product) 
     { 
      var poco = new Poco 
         { 
          Id = version.SelectToken("id").ToString() 
         }; 
     } 
    } 
} 

Quindi la mia domanda, come posso scorrere su dizionari nidificati usando JSON.Net?

risposta

6

Trovato questa domanda cercando di capire come analizzare JSON.NET in C#. Spero che la mia risposta aiuti qualcun altro ...

Ho scritto questo codice per aiutarmi a analizzare un oggetto JSON casuale e analizzare la struttura. È un po 'approssimativo e probabilmente non gestisce tutti gli scenari, ma fa il trucco. In questo momento sta solo memorizzando le posizioni in un dizionario, ma dovrebbe essere abbastanza facile vedere cosa sta facendo e modificarlo per fare ciò che vuoi:

static void Main(string[] args) 
{ 
    Dictionary<string, string> nodes = new Dictionary<string, string>(); 

    // put your JSON object here 
    JObject rootObject = JObject.Parse("{\"world\": {\"hello\": \"woo\", \"foo\": \"bar\", \"arr\": [\"one\", \"two\"]}}"); 

    ParseJson(rootObject, nodes); 

    // nodes dictionary contains xpath-like node locations 
    Debug.WriteLine(""); 
    Debug.WriteLine("JSON:"); 
    foreach (string key in nodes.Keys) 
    { 
     Debug.WriteLine(key + " = " + nodes[key]); 
    } 
} 

/// <summary> 
/// Parse a JSON object and return it as a dictionary of strings with keys showing the heirarchy. 
/// </summary> 
/// <param name="token"></param> 
/// <param name="nodes"></param> 
/// <param name="parentLocation"></param> 
/// <returns></returns> 
public static bool ParseJson(JToken token, Dictionary<string, string> nodes, string parentLocation = "") 
{ 
    if (token.HasValues) 
    { 
     foreach (JToken child in token.Children()) 
     { 
      if (token.Type == JTokenType.Property) 
       parentLocation += "/" + ((JProperty)token).Name; 
      ParseJson(child, nodes, parentLocation); 
     } 

     // we are done parsing and this is a parent node 
     return true; 
    } 
    else 
    { 
     // leaf of the tree 
     if (nodes.ContainsKey(parentLocation)) 
     { 
      // this was an array 
      nodes[parentLocation] += "|" + token.ToString(); 
     } 
     else 
     { 
      // this was a single property 
      nodes.Add(parentLocation, token.ToString()); 
     } 

     return false; 
    } 
} 
Problemi correlati