Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JSON.Net to write a property name

Tags:

json

c#

json.net

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?

like image 866
shergill Avatar asked Sep 07 '11 01:09

shergill


People also ask

What is JSON property name?

The Jackson Annotation @JsonProperty is used on a property or method during serialization or deserialization of JSON. It takes an optional 'name' parameter which is useful in case the property name is different than 'key' name in JSON.

What is JSON property C#?

JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.

Is JSON NET the same as Newtonsoft JSON?

Thanks. Json.NET vs Newtonsoft. Json are the same thing. You must be trying to use the same code with different versions of Json.NET.

How does JSON NET work?

Json uses reflection to get constructor parameters and then tries to find closest match by name of these constructor parameters to object's properties. It also checks type of property and parameters to match. If there is no match found, then default value will be passed to this parameterized constructor.


1 Answers

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();
like image 86
BoltClock Avatar answered Oct 03 '22 21:10

BoltClock