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?
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.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With