2012-04-02 15 views
10

Devo selezionare alcuni valori da una risposta JSON. Sto usando json.net, bene con le cose più semplici, ma non sembra che ci sia molta documentazione/tutorial su qualcosa che è passato. Nell'esempio json sotto devo selezionare tutte le età:JSON.NET Selezione degli elementi nella matrice con linq

{ 
"teacherHolder": [{ 
    "id": 200000001, 
    "name": "Mr Test", 
    "class": "a4", 
    "students": [{ 
     "id": "100532469", 
     "name": "ben" 
    }, 
    { 
     "id": "100506025", 
     "name": "bill" 
    }, 
    { 
     "id": "100000447", 
     "name": "bob" 
    }] 

}] 

}

Ho provato questo e altre variazioni:

var stuff = response["teacherHolder"].Children()["students"]; 

var names = from y in stuff.Children().Values() 
        select y["name"]; 

e questo:

var names= response["teacherHolder"] 
      .Select(s => (string)s.SelectToken("students[0].name")).ToList(); 

risposta è un JObject da una richiesta web. Ho appena rimetto questo:

[{"Key":"Newtonsoft.Json.Linq.JEnumerable`1[Newtonsoft.Json.Linq.JToken]","Value":"Newtonsoft.Json.Linq.JEnumerable`1[Newtonsoft.Json.Linq.JToken]"}] 

I risultati sono poi messi in un dizionario.

Qualche idea su come procedere? so che sarà semplice, non ho trovato la combinazione giusta.

risposta

20

Se si desidera ottenere i nomi di tutti gli studenti di tutti gli insegnanti, si può fare per esempio come questo:

var students = response["teacherHolder"].Children()["students"]; 

var names = students.Children()["name"]; 

Oppure, come un'altra opzione:

var names = from teacher in response["teacherHolder"] 
      from student in teacher["students"] 
      select student["name"]; 

Se si desidera come IEnumerable<string>, aggiungi Value<string>() alla fine dello select. Oppure aggiungi Values<string>(), se hai la prima opzione.

Ma in genere è preferibile creare tipi per il modello a oggetti, in modo da poter lavorare con essi come con oggetti normali e non come oggetti JSON speciali.

Se si dispone di questo, si potrebbe fare qualcosa di simile:

var names = from teacher in response.TeacherHolder 
      from student in teacher.Students 
      select student.Name; 
+0

Hi svick im utilizzando il primo metodo - ma sto ottenendo indietro è: {Newtonsoft.Json.Linq.JEnumerable } nella variabile nomi? – gdp

+1

Sì, è per questo che ho detto che è necessario aggiungere 'Valori ()' se si desidera una raccolta di 'string's. – svick

+1

Ciao svick ho aggiunto i valori () fino alla fine. è ora: var names = students.Children() ["name"]. Valori (); – gdp

Problemi correlati