This project has moved. For the latest updates, please go here.

Serializing part of object

May 3, 2009 at 2:04 PM
I'm trying to implement serializing and deserializing an .NET object to a JSON object while also serializing the type and potentially some extra attributes which are not a property of the object.
If the type is serialized with the object, I can deserialize the correct type if the type is not known at runtime. This is the case when serializing a subclassed object, or when serializing a graph of objects of different types.

So I'd like for example to serialize an Employee e containing the fields 'FirstName' and 'LastName' like
      <tt> {"CLRType": "MyNamespace.Employee", "FirstName": "John", "LastName": "Doe"}
</tt> ...and being able to deserialize this.

I'm missing two features: (de)serializing something which is not a property (namely, obj.GetType().ToString()), and a way to partially parse an object: something like JObject.Load() with the object already openened.

Browsing the code it seems I could create my own JsonConverter, which would read my own custom fields ("CLRType" in this case"), and then use functionality from JContainer.ReadContentFrom() or something like that. But the problem is that ReadContentFrom() is internal, and I'd like to create the object myself (since I know the type: it must be of type CLRType), and then pass this object to be filled.

How could I do this? Any pointers would be appreciated.

May 4, 2009 at 7:16 AM
For later reference, I got it working with the following code in a JsonConverter:

        public override void WriteJson(JsonWriter writer, object value) {
            var j = JObject.FromObject(value);
            var typeAsToken = JToken.FromObject(value.GetType().ToString());
            j.AddFirst(new JProperty("CLRType", typeAsToken));
            Serializer().Serialize(writer, j);

        public override object ReadJson(JsonReader reader, Type objectType) {
            var j = JObject.Load(reader);
            string typeAsString = (string)j["CLRType"];
            Type type = Type.GetType(typeAsString, true);
            var valueTokenReader = new JsonTokenReader(j);
            object value = Serializer().Deserialize(valueTokenReader, type);
            return value;

[It's actually quite simple if you know what to do :-]