Jonathan Kittell
Jonathan Kittell

Reputation: 7493

Json.Net deserialization results in null objects

I am working on deserializing a json response and I am getting null values:

{
    "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": ""
            }
        }]
    }
}

This is the class I use to serialize the json above.

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

The response contains more than one biography:

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

Why are all of the values returning null for the Response class?

In this case T is Response:

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

Upvotes: 1

Views: 86

Answers (1)

Martijn van Put
Martijn van Put

Reputation: 3313

In order to deserialize you need to create a class that contains the response property.

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

Then use the RootObject class to deserialize.

Upvotes: 2

Related Questions