2013-11-14 14 views
12

Hi there Ho JSON che assomiglia a questo:ottenere i valori e le chiavi in ​​oggetto JSON utilizzando Json.Net C#

{ 
    "Id": " 357342524563456678", 
    "title": "Person", 
    "language": "eng", 
    "questionAnswer": [ 
     { 
      "4534538254745646.1": { 
       "firstName": "Janet", 
       "questionNumber": "1.1" 
      } 
     } 
    ] 
} 

Ora ho scritto un codice che si ripete nel corso degli oggetti nella matrice questionAnswer e poi viene il nome dell'oggetto che è 4534538254745646.1. Ora sto cercando di salvare la chiave di ogni oggetto e il valore, ma sto solo riuscendo a ottenere il valore.

Come farei questo, qui è il mio codice:

JToken entireJson = JToken.Parse(json); 
JArray inner = entireJson["questionAnswer"].Value<JArray>(); 


foreach(var item in inner) 
{ 
    JProperty questionAnswerDetails = item.First.Value<JProperty>(); 
    //This line gets the name, which is fine 
    var questionAnswerSchemaReference = questionAnswerDetails.Name; 
    var properties = questionAnswerDetails.Value.First; 

    //This only gets Janet 
    var key = properties.First; 
    var value = properties.Last;          
} 

Quindi al momento Im solo in grado di ottenere Janet, ma voglio anche il campo Nome. Voglio poi prendere questo e aggiungere a un dizionario cioè

Dictionary<string, string> details = new Dictionary<string, string>(); 
//suedo 
foreach(var item in questionAnswerObjects) 
details.Add(firstName, Janet); 
//And then any other things found below this 

risposta

14

ecco che codice completo che ottiene le chiavi e valori per ogni elemento nell'oggetto nella matrice:

string key = null; 
string value = null; 

foreach(var item in inner) 
{ 
    JProperty questionAnswerDetails = item.First.Value<JProperty>(); 

    var questionAnswerSchemaReference = questionAnswerDetails.Name; 

    var propertyList = (JObject)item[questionAnswerSchemaReference]; 

    questionDetails = new Dictionary<string, object>(); 

    foreach (var property in propertyList) 
    { 
     key = property.Key; 
     value = property.Value.ToString(); 
    } 

    questionDetails.Add(key, value);    
} 

posso ora aggiungi chiave e valore al dizionario

Problemi correlati