使用减去属性名称反序列化Json

时间:2016-04-13 20:23:29

标签: c# json deserialization restsharp json-deserialization

我有一个JSON返回如下。

   {
    "id": 100,
    "name": "employer 100",
    "externalId": "100-100",
    "networkId": 1000,
    "address": {
        "street-address": "1230 Main Street",
        "locality": "Vancouver",
        "postal-code": "V6B 5N2",
        "region": "BC",
        "country-name": "CA"
    }
   }

所以我创建了一个类来反序列化上面的json。

    public class Employer
        {
            public int id { get; set; }
            public string name { get; set; }
            public string externalId { get; set; }
            public int networkId { get; set; }
            public Address address { get; set; }
        }
    public class Address
        {
            public string street_address { get; set; }
            public string locality { get; set; }
            public string postal_code { get; set; }
            public string region { get; set; }
            public string country_name { get; set; }
        }
var response = _client.Execute(req); 
return _jsonDeserializer.Deserialize <Employer> (response);

但我无法从Json字符串中获取 街道地址,邮政编码和国家/地区名称 。我认为因为Json输出键包含&#34;&#34; - &#34;&#34; (结果我得到了空白。)

那么我怎么能解决我的问题?

2 个答案:

答案 0 :(得分:3)

在属性中使用DeserializeAs属性:

[DeserializeAs(Name = "postal-code")]
public string postal_code { get; set; }

这允许您在json中设置相同的属性,该属性映射到类中的属性,允许该属性具有与子的不同的名称。

https://github.com/restsharp/RestSharp/wiki/Deserialization

答案 1 :(得分:0)

如果您正在使用JSON.net,请使用属性上的属性指定它们应匹配的名称:

public class Employer
{
    public int id { get; set; }
    public string name { get; set; }
    public string externalId { get; set; }
    public int networkId { get; set; }
    public Address address { get; set; }
}
public class Address
{

    [JsonProperty("street-address")]
    public string street_address { get; set; }
    public string locality { get; set; }
    [JsonProperty("postal-code")]
    public string postal_code { get; set; }
    public string region { get; set; }
    [JsonProperty("country-name")]
    public string country_name { get; set; }
}
相关问题