Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an extra property into a serialized JSON string using json.net?

Tags:

json

json.net

I am using Json.net in my MVC 4 program.

I have an object item of class Item.

I did: string j = JsonConvert.SerializeObject(item);

Now I want to add an extra property, like "feeClass" : "A" into j.

How can I use Json.net to achieve this?

like image 346
peter Avatar asked Sep 09 '13 06:09

peter


People also ask

What does Jsonproperty attribute do?

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.

What is a serialized JSON string?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

Which of the following attribute should be used to indicate the property must not be serialized while using .JSON serializer?

Apply a [JsonIgnore] attribute to the property that you do not want to be serialized.

What is Jsonobject attribute C#?

JsonObjectAttribute is used to support Json schema definition. -- while these three properties are used only for schema definition, most other properties of JsonObjectAttribute affect serialization as well.


1 Answers

You have a few options.

The easiest way, as @Manvik suggested, is simply to add another property to your class and set its value prior to serializing.

If you don't want to do that, the next easiest way is to load your object into a JObject, append the new property value, then write out the JSON from there. Here is a simple example:

class Item {     public int ID { get; set; }     public string Name { get; set; } }  class Program {     static void Main(string[] args)     {         Item item = new Item { ID = 1234, Name = "FooBar" };         JObject jo = JObject.FromObject(item);         jo.Add("feeClass", "A");         string json = jo.ToString();         Console.WriteLine(json);     } } 

Here is the output of the above:

{   "ID": 1234,   "Name": "FooBar",   "feeClass": "A" } 

Another possibility is to create a custom JsonConverter for your Item class and use that during serialization. A JsonConverter allows you to have complete control over what gets written during the serialization process for a particular class. You can add properties, suppress properties, or even write out a different structure if you want. For this particular situation, I think it is probably overkill, but it is another option.

like image 113
Brian Rogers Avatar answered Sep 30 '22 17:09

Brian Rogers