Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Json.net - partial custom serialization of a c# object

I ma using Newtonsofts' Json.Net to serialize some and array of objects to json. The objects have a common set of properties but also have Meta property which is a dictionary

During serialization I want the key value pairs to be added to my json object as if they where root level properties, like this...

 {
    id: 1,
    name:'jeff',
    food:'spinch',
    spoon: 'ýes'
 }  

Not like this:

 {
    id: 1,
    name:'jeff',
    meta:{
       food:'spinch',
       spoon: 'ýes'
    }
 } 

I have dug through JsonSerializerSettings but cant seem to spot where I can jump in and override???

like image 320
David Avatar asked Mar 23 '11 11:03

David


2 Answers

You can do this by creating your own JsonConverter and then adding an attribute to the class you want to serialize [JsonConverter(typeof(MyConverter))]

Example here - http://www.lostechies.com/blogs/rhouston/archive/2008/02/25/a-custom-converter-for-json-net.aspx

like image 147
Stuart Avatar answered Oct 13 '22 22:10

Stuart


If your dictionary is a string to object dictionary could can simply use the [JsonExtensionData] attribute:

[JsonExtensionData]
public Dictionary<string, object> Meta { get; set; }

See How to serialize a Dictionary as part of its parent object using Json.Net.

like image 2
Dejan Avatar answered Oct 13 '22 21:10

Dejan