Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is JSON.NET is not working with inheritance while deserializing

I am deserializing the JSON string to root object by using the following class which works fine .

[Serializable]
    public class MoviesListRootObject
    {
        public int count { get; set; }
        public Pagination pagination { get; set; }
        public List<Response> response { get; set; }
    }

...................................

var json = wc.DownloadString(jsonRequestURL);
var rootObj = JsonConvert.DeserializeObject<MoviesListRootObject>(json);

But if I am generalizng the root object bt creating parent class and then inheriting from it , then I get null after deserialization!!!!

[Serializable]
    public class RootObject
    {
        public int count { get; set; }
        public Pagination pagination { get; set; }
    }

[Serializable]
    public class MoviesListRootObject:RootObject
    {
        public List<MovieResponse> movieResponse { get; set; }

    }

..............................................

 var json = wc.DownloadString(jsonRequestURL);
 var rootObj = JsonConvert.DeserializeObject<MoviesListRootObject>(json);
like image 415
Simsons Avatar asked Sep 12 '12 05:09

Simsons


People also ask

What is Deserializing JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

How does JSON deserialize work?

In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.

How do I use JSON deserializer?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.


1 Answers

It is quite simple and out of the box support provided by json.net, you just have to use the following JsonSettings while serializing and Deserializing:

JsonConvert.SerializeObject(graph, Formatting.None, new JsonSerializerSettings() {
    TypeNameHandling = TypeNameHandling.All,
    TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
});

and for Deserializing use the below code:

JsonConvert.DeserializeObject(Encoding.UTF8.GetString(bData), type,
    new JsonSerializerSettings() {
    TypeNameHandling = TypeNameHandling.All
});

Just take a note of the JsonSerializerSettings object initializer, that is important for you.

like image 67
Sunil S Avatar answered Sep 21 '22 06:09

Sunil S