2

I have a Parent class and a Child class, the json string is containing properties of Child class but when I do a DeserializeObject I can't get those properties because Child became a Parent.

For example :

class Data {
    public List<Parent> Parents;
}

class Parent {
    public string Foo;
}

class Child : Parent {
    public string Bar;
}

var data = new Data { Parents = new List<Parent> { new Child{Bar = "a"} } };
Console.WriteLine(data.Parents.Count); // <= it prints 1
Console.WriteLine(data.Parents.OfType<Child>().Count()); // <= it prints 1

var dataJson = JsonConvert.SerializeObject(data);
data = JsonConvert.DeserializeObject<Data>(dataJson);

Console.WriteLine(data.Parents.Count); // <= it prints 1
Console.WriteLine(data.Parents.OfType<Child>().Count()); // <= it prints 0 instead of 1

What can I do about that ? Newtonsoft.Json can manage to do what I want ?

1 Answer 1

5

Use JsonSerializerSettings' TypeNameHandling

var settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All };

var dataJson = JsonConvert.SerializeObject(data, settings);
data = JsonConvert.DeserializeObject<Data>(dataJson, settings);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.