Json.Net反序列化返回空值

时间:2014-07-12 01:02:37

标签: c# json.net deserialization

我正在使用Petfinder API并尝试在我的C#代码中返回一个根对象。我使用Json类生成器生成类,但Deserialize函数返回null。

这是我的C#代码:

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

        }

Petfinder对象定义为:

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

json字符串的前几行如下:

{ “@编码”: “ISO-8859-1”, “@版本”: “1.0”, “petfinder”:{ “@的xmlns:的xsi”: “http://www.w3.org/2001/XMLSchema-instance”, “lastOffset”: { “$吨”: “25”}, “宠物”:{ “宠物”:[{ “选项”:{ “选项”:[{ “$吨”: “hasShots”},{ “$吨”:”改变了“},{”$ t“:”housetrained“}]},”品种“:{”品种“:{”$ t“:”国内中型发型“}},”shelterPetId“:{},”状态“ :{“$ t”:“A”},“name”:{“$ t”:“Jasmine”},...

如果这有帮助的话。

我是json.net的新手。我做错了什么?

1 个答案:

答案 0 :(得分:0)

您的课程错了,请查看json2csharp.com的输出,了解您提供的示例json。显然,__invalid_name_$t需要手动修复,并使用[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; }
}
相关问题