Selectively applying TypeNameHandling to class members - how to?

Mar 31, 2010 at 11:34 AM

Hi, I want to build an universal message wrapper class and serialize it to Json. This class contains a collection of headers and the message body, which can be any type.

I want to serialize it to plain Json, so I'm using TypeNameHandling = TypeNameHandling.Objects in serializer settings, so type names get serialized along with the data.

Here's my class and json it produces:

 

    public class MessageWrapper2
    {
        public MessageWrapper2()
        {
            Headers = new Hashtable();
        }
        
        public Hashtable Headers { get; set; }
        public object Body { get; set; }
    }

 

 

    public class MessageWrapper2
    {
        public MessageWrapper2()
        {
            Headers = new Hashtable();
        }
        
        public Hashtable Headers { get; set; }
        public object Body { get; set; }
    }

JSON:

 

{"$type":"Tests.MessageWrapper2, Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
"Headers":{"$type":"System.Collections.Hashtable, mscorlib, Version=2.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089","DeliverAt":"yesterday!"},
"Body":{"$type":"Tests.TestMessage1, Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null","Id":893239}
}

I'd like to have "$type" field only in the contents of Body property, there's no need to have $type for the MessageWrapper2 class and Headers property because it only makes the message bigger. Ideally, the json should look like

 

{
"Headers":{"DeliverAt":"yesterday!"},
"Body":{"$type":"Tests.TestMessage1, Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null","Id":893239}
}

Can you please help me how to customize the serializer or my MessageWrapper2 class to serialize & deserialize json in such way?

Many thanks

RG

 

 

 

 

 

Coordinator
Apr 2, 2010 at 10:59 AM

I have added TypeNameHandling to the JsonProperty attribute.

http://json.codeplex.com/SourceControl/list/changesets

 

Apr 2, 2010 at 12:37 PM

Thanks, that's great. I'll give it a try asap.

RG