0
votes

I'm using the Petfinder API and trying to return a root object in my C# code. I used the Json class generator to generate the classes, but the Deserialize function is returning nulls.

This is my C# code:

using (var client = new WebClient())
        {
            var json = new WebClient().DownloadString("http://api.petfinder.com/shelter.getPets?format=json&key=<key>&id=<id>");
            Petfinder deserializedPet = JsonConvert.DeserializeObject<Petfinder>(json);

        }

The Petfinder object is defined as:

internal class Petfinder
{

    [JsonProperty("@xmlns:xsi")]
    public string XmlnsXsi { get; set; }

    [JsonProperty("lastOffset")]
    public LastOffset LastOffset { get; set; }

    [JsonProperty("pets")]
    public Pets Pets { get; set; }

    [JsonProperty("header")]
    public Header Header { get; set; }

    [JsonProperty("@xsi:noNamespaceSchemaLocation")]
    public string XsiNoNamespaceSchemaLocation { get; set; }
}

The first few lines of the json string is as follows:

{"@encoding":"iso-8859-1","@version":"1.0","petfinder":{"@xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","lastOffset":{"$t":"25"},"pets":{"pet":[{"options":{"option":[{"$t":"hasShots"},{"$t":"altered"},{"$t":"housetrained"}]},"breeds":{"breed":{"$t":"Domestic Medium Hair"}},"shelterPetId":{},"status":{"$t":"A"},"name":{"$t":"Jasmine"},...

If that helps at all.

I'm a newbie to json.net. What am I doing wrong?

1

1 Answers

0
votes

Your class is wrong, take a look at the output from json2csharp.com for the example json you provided. Obviously the __invalid_name_$t needs to be manually fixed and the mapped using [JsonProperty].

public class LastOffset
{
    public string __invalid_name__$t { get; set; }
}

public class Option
{
    public string __invalid_name__$t { get; set; }
}

public class Options
{
    public List<Option> option { get; set; }
}

public class Breed
{
    public string __invalid_name__$t { get; set; }
}

public class Breeds
{
    public Breed breed { get; set; }
}

public class ShelterPetId
{
}

public class Status
{
    public string __invalid_name__$t { get; set; }
}

public class Name
{
    public string __invalid_name__$t { get; set; }
}

public class Pet
{
    public Options options { get; set; }
    public Breeds breeds { get; set; }
    public ShelterPetId shelterPetId { get; set; }
    public Status status { get; set; }
    public Name name { get; set; }
}

public class Pets
{
    public List<Pet> pet { get; set; }
}

public class Petfinder
{
    public string __invalid_name__@xmlns:xsi { get; set; }
    public LastOffset lastOffset { get; set; }
    public Pets pets { get; set; }
}

public class RootObject
{
    public string __invalid_name__@encoding { get; set; }    
    public string __invalid_name__@version { get; set; }
    public Petfinder petfinder { get; set; }
}