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?
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?
You could use ExpandoObject. Deserialize to that, add your property, and serialize back.
Pseudocode:
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:Here is the output of the above:
Another possibility is to create a custom
JsonConverter
for yourItem
class and use that during serialization. AJsonConverter
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.