2011-09-07 16 views
8

Sto usando JSON.net per scrivere alcuni JSON in C#. Posso produrre JSON come questo
Utilizzo di JSON.Net per scrivere il nome di una proprietà

{ 
    "id": "234", 
    "name": "abc" 
} 

Quello che vorrei fare è ottenere è questo

{ 
    "DATA": { 
     "id": "234", 
     "name": "abc" 
    } 
} 

Qui è il codice json.net sto usando

StringBuilder sb = new StringBuilder(); 
    StringWriter sw = new StringWriter(sb); 
    JsonWriter jsonWriter = new JsonTextWriter(sw); 
    jsonWriter.Formatting = Formatting.Indented; 



     jsonWriter.WriteStartObject();     
      jsonWriter.WritePropertyName("id"); 
      jsonWriter.WriteValue("234"); 
      jsonWriter.WritePropertyName("name"); 
      jsonWriter.WriteValue("abc"); 
     jsonWriter.WriteEndObject(); 

può suggerisci come aggiungere la sezione "DATI" ad esso?

risposta

13

rendere l'oggetto root, quindi scrivere il nome della proprietà "DATA", quindi scrivere l'oggetto che hai appena scritto:

jsonWriter.WriteStartObject(); 
    jsonWriter.WritePropertyName("DATA"); 
    jsonWriter.WriteStartObject(); 
     jsonWriter.WritePropertyName("id"); 
     jsonWriter.WriteValue("234"); 
     jsonWriter.WritePropertyName("name"); 
     jsonWriter.WriteValue("abc"); 
    jsonWriter.WriteEndObject(); 
jsonWriter.WriteEndObject(); 
+0

impressionante !. molte grazie – shergill

Problemi correlati