JSONObject反序列化不反序列化

JSONObject Deserialization Does not Deserialize

这难倒了我。这是我简化的 C# class 定义:

public class Countries
{
    string TotalCount { get; set; }
    public List<Ctry> Country { get; set; }
}
public class Ctry
{
    string CountryId { get; set; }
    string CountryName { get; set; }
}

我进行的 REST 调用成功并且 returns 以下 JSON 我可以在 'content' 变量中看到:

{"TotalCount":1,"Country":[{"CountryId":1,"CountryName":"USA"}]}

这是我的 C# 反序列化代码:

var content = response.Content;
countryList =  JsonConvert.DeserializeObject<Countries>(content);

反序列化后,我希望国家/地区数据位于 countryList 对象中。但是 countryList 中没有显示任何数据!是什么赋予了?也没有异常或错误!

您的问题是 JSON.NET 默认为驼峰式 属性 名称。这是您的代码默认查找的内容:

{"country":[{"countryId":"1","countryName":"USA"}]}

您需要为您的模型手动声明 JSON.NET 属性 名称:

public class Countries
{
    [JsonProperty(PropertyName = "TotalCount")]
    string TotalCount { get; set; }

    [JsonProperty(PropertyName = "Country")]
    public List<Ctry> Country { get; set; }
}
public class Ctry
{
    [JsonProperty(PropertyName = "CountryId")]
    string CountryId { get; set; }

    [JsonProperty(PropertyName = "CountryName")]
    string CountryName { get; set; }
}

我对此进行了测试,它适用于您的数据。

作为旁注,我声明了所有 属性 名称,因为我喜欢保持对序列化和反序列化的手动控制,在你的情况下,你可以通过声明多大小写单词来解决问题.

如果您不想手动定义 属性 名称,您也可以通过调整属性的保护级别来解决此问题:

public class Countries
{
    public string TotalCount { get; set; }
    public List<Ctry> Country { get; set; }
}
public class Ctry
{
    public string CountryId { get; set; }
    public string CountryName { get; set; }
}

这样 JSON.NET 可以自动匹配 属性 可以公开访问的名称。

@Tom W - JSON.NET 会尽可能自动转换类型,int 到 string 和 string 到 int 都可以。