0

Let us say I have the following:

public class Parent
{
    public string Id;
}

public class FirstChild:Parent
{
    public string FirstName;
}

public class SecondChild:Parent
{
    public string LastName;
}

and I have a Json of type FirstChild or SecondChild, how can I deserialize it to suitable type without having to check contents of serialized JSON knowing that I cann't control the serialization process?

I have tried the solution mentioned here, but what I am getting is the Parent object (fields of children are gone).

JsonSerializerSettings settings = new JsonSerializerSettings 
{
    TypeNameHandling = TypeNameHandling.All 
};
var deserialized = JsonConvert.DeserializeObject<Parent>(
    Serialized FirstChild/SecondChild, 
    settings);

A Json Sample:

{\"firstName\":\"John\",\"id\":\"1\"}
Yahya Hussein
  • 8,767
  • 15
  • 58
  • 114

1 Answers1

2

To deserialise derived types correctly using Newtonsoft.Json, the JSON string needs to contain an element with name $type and value containing the type name. For example, a correctly serialised FirstChild object would look like this:

{
  "$type": "Your.Name.Space.FirstChild, Your.Name.Space",
  "FirstName": "Blah",
  "Id": "1"
}

To do this, ensure that you serialise with TypeNameHandling.All:

JsonSerializerSettings settings = new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.All
};

var json = JsonConvert.SerializeObject(yourFirstParentObject, settings);

Now your deserialisation code will work correctly.

DavidG
  • 113,891
  • 12
  • 217
  • 223
  • Thanks, what do you mean by "$type": "Your.Name.Space.FirstChild, Your.Name.Space"? how can I make it happen? adding it to my model? – Yahya Hussein Jan 23 '18 at 10:27
  • The issue is that it is serialized by a third party library, I can not control the serialization – Yahya Hussein Jan 23 '18 at 10:31
  • Then you either need to tell them to fix that or you need to specify the correct type when deserialising. – DavidG Jan 23 '18 at 10:32
  • I c, thank you, the library I am using is Masstransit and it is designed to behave like this, so I think updating the serialization is not an option, will try to fix it another way around I guess. – Yahya Hussein Jan 23 '18 at 10:34
  • Are you sure you can't change it? https://gist.github.com/MikeGoldsmith/2e07b64cf25ffd259ec6 – DavidG Jan 23 '18 at 10:41