为什么JSON.NET在反序列化时不使用继承

Sim*_*ons 9 .net c# json.net c#-4.0

我通过使用以下类正常将JSON字符串反序列化为根对象.

[Serializable]
    public class MoviesListRootObject
    {
        public int count { get; set; }
        public Pagination pagination { get; set; }
        public List<Response> response { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

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

var json = wc.DownloadString(jsonRequestURL);
var rootObj = JsonConvert.DeserializeObject<MoviesListRootObject>(json);
Run Code Online (Sandbox Code Playgroud)

但是,如果我在创建父类,然后继承它的根对象bit,那么在反序列化后我得到null!

[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; }

    }
Run Code Online (Sandbox Code Playgroud)

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

 var json = wc.DownloadString(jsonRequestURL);
 var rootObj = JsonConvert.DeserializeObject<MoviesListRootObject>(json);
Run Code Online (Sandbox Code Playgroud)

key*_*eyr 0

假设 json 字符串如下所示

{"movieResponse":[{"Rating":"Good"}],"count":1,"pagination":{"PageIndex":1}}
Run Code Online (Sandbox Code Playgroud)

我发现它对我来说效果很好。我目前使用 Json.net 4.5 r11

如果你序列化对象的时候类结构看起来像

[Serializable]
public class MoviesListRootObject
{
        public int count { get; set; }
        public Pagination pagination { get; set; }
        public List<Response> response { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

json 字符串如下所示

{"count":1,"pagination":{"PageIndex":1},"response":[{"Rating":"Good"}]}
Run Code Online (Sandbox Code Playgroud)

现在您正在使用新结构进行反序列化,那么您将得到 null,movieResponse因为新结构中的属性已更改。

为了解决这个问题,创建一个新的自定义 jsonConverter 派生JsonConverter并以编程方式创建您的对象。请查看链接json-deserialization-with-jsonnet-class以了解一些想法。如果您已经知道这一点并且问题仍然存在,请更新问题并提供更多详细信息,例如使用的 Json.net 版本、json 字符串、完整的类结构等

HTH。