8

(Using Newtonsoft JSON.NET)

Hi I've got a problem when deserializing a list of events where Event is the base type and e.g. ResourceEvent is a subclass. If I just do a serialize and then deserialize everything works ok and the list contains the ResourceEvents - however I store those using EF7 into a jsonb column in postgres.

When I get the JSON payload from postgres it has reordered (but JSON legal) the properties. When I try to deserialize using Newtonsoft JSON.net it only give me a list with base types Event and not the subclass ResourceEvent.

I've added the two highly stripped examples where the differences is where the "Type" property is on different places. The ordering of other properties has also been scrambeled in the classes. I've got no annotations on the classes at all.

This payload successfully deseralizes:

json
{
    "$type": "System.Collections.Generic.List`1[[Event, Tests]], mscorlib",
    "$values": [
        {
            "$type": "ResourceConfigurationEvent, Tests",
            /* Properties */
            "Resources": {
                /* Properties */                
            },
            "Type": 1            
        }
    ]
}

This payload unsuccessfully deserializes:

json
{
    "$type": "System.Collections.Generic.List`1[[Event, Tests]], mscorlib",
    "$values": [
        {
            "Type": 1,            
            "$type": "ResourceConfigurationEvent, Tests",
            /* Properties */
            "Resources": {
                /* Properties */                
            },
        }
    ]
}
4
  • 2
    Please read How to Ask and provide a minimal reproducible example, focus on minimal.
    – CodeCaster
    Jun 1, 2016 at 8:43
  • Scroll...scroll...scroll...scroll...scroll...scroll...nah, to much to read.
    – Renatas M.
    Jun 1, 2016 at 8:53
  • can you provide class definition , would suggest not to de-serialize dictionary , but some thing like this [IgnoreDataMember] public Dictionary<yourkey, yourObject>>(); [DataMember(Name = "name you want")] public IEnumerable<yourObject> ObjectToStore
    – Amit Pore
    Jun 1, 2016 at 10:14
  • Stripped down the payload - sorry for the inconvenience. I'm not serializing a dictionary, just a List<Event> and all classes do not have any annotation at all. Jun 1, 2016 at 13:21

1 Answer 1

11

Json.Net normally expects the $type metadata to be the first property of each object for best efficiency in deserialization. If the $type does not appear first, then Json.Net assumes it isn't there. That is why you are getting different results when the properties are reordered.

Fortunately, Json.Net provides a MetadataPropertyHandling setting to allow it to cope with this situation. If you set MetadataPropertyHandling to ReadAhead it should solve your problem. Note that this will have an impact on performance.

Here is a code sample from the documentation.

string json = @"{
  'Name': 'James',
  'Password': 'Password1',
  '$type': 'MyNamespace.User, MyAssembly'
}";

object o = JsonConvert.DeserializeObject(json, new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.All,
    // $type no longer needs to be first
    MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead
});

User u = (User)o;

Console.WriteLine(u.Name);
// James
4
  • 2
    Thanks! Works like a charm! I'll check with the postgres guys if they can preserve ordering in a 'jsonb' column. Again many thanks for the prompt answer! :) Jun 1, 2016 at 18:47
  • 1
    you are a true life saver! Mar 2, 2017 at 0:36
  • One thing you need to keep in mind is that the JsonSerializerSettings listed in this answer does not just store the namespace-qualified class name in the type information, but also the name of the origin assembly within which the C# object lives. Ensure that the name of the destination assembly where the deserialization takes place is not different from that of the source assembly within which the serialization happened.
    – Najeeb
    Apr 14, 2020 at 17:04
  • 1
    @Najeeb if this is an issue, you can implement a custom ISerializationBinder to change the way the $type information is written to the JSON. There is a sample in the documentation here. Dec 18, 2020 at 19:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.