11

I am using JSON.net to write some json in C#. I can produce JSON like this

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

What i would like to do is get is this

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

Here is the json.net code i'm using

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

can you suggest how to add the 'DATA' section to it?

1 Answer 1

17

Make the root object, then write the property name "DATA", then write the object you just wrote:

jsonWriter.WriteStartObject();
    jsonWriter.WritePropertyName("DATA");
    jsonWriter.WriteStartObject();
        jsonWriter.WritePropertyName("id");
        jsonWriter.WriteValue("234");
        jsonWriter.WritePropertyName("name");
        jsonWriter.WriteValue("abc");
    jsonWriter.WriteEndObject();
jsonWriter.WriteEndObject();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.