Json.Net反序列化导致null对象

时间:2015-03-15 15:26:28

标签: c# json

我正在进行反序列化json响应,我得到空值:

{
    "response": {
        "status": {
            "version": "4.2",
            "code": 0,
            "message": "Success"
        },
        "start": 0,
        "total": 12,
        "biographies": [{
            "text": "\"Radiohead\" are an English alternative rock band from Abingdon, Oxfordshire, formed in 1985. The band consists of Thom Yorke (vocals, guitars, piano), Jonny Greenwood (guitars, keyboards, other instruments), Ed O'Brien (guitars, backing vocals), Colin Greenwood (bass, synthesisers) and Phil Selway (drums, percussion).",
            "site": "wikipedia",
            "url": "http://en.wikipedia.org/wiki/Radiohead",
            "license": {
                "type": "cc-by-sa",
                "attribution": "n/a",
                "url": ""
            }
        }]
    }
}

这是我用来序列化json的类。

public class Response : IResponse
{
    public Status status { get; set; }
    public string start { get; set; }
    public string total { get; set; }
    public List<Biography> biographies { get; set; } 
}

回复包含多个传记:

public class Biography
{
    public string text { get; set; }
    public string site { get; set; }
    public string url { get; set; }
    public LicenseInfo license { get; set; }
}

public class LicenseInfo
{
    public string type { get; set; }
    public string attribution { get; set; }
    public string url { get; set; }
}

为什么Response类的所有值都返回null?

在这种情况下,TResponse

return string.IsNullOrEmpty(response) ? default(T) : JsonConvert.DeserializeObject<T>(response);

1 个答案:

答案 0 :(得分:2)

为了反序列化,您需要创建一个包含response属性的类。

public class RootObject
{
     public Response response { get; set; }
}

然后使用RootObject类进行反序列化。