【问题标题】:Deserialize Json with minus in property name [duplicate]使用属性名称中的减号反序列化 Json [重复]
【发布时间】:2016-04-13 20:23:29
【问题描述】:

我有一个如下的 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 输出键包含 ""-"" (因此我得到空值)。

那么我该如何解决我的问题呢?

【问题讨论】:

  • 你使用哪个库进行反序列化?
  • 更新了我对 RestSharp 的回答

标签: c# json deserialization restsharp json-deserialization


【解决方案1】:

在你的属性上使用 DeserializeAs 属性:

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

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

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

【讨论】:

  • 如果 OP 使用 JsonNet
  • 我假设基于 JsonDeserializer.Deserialize 他们是,但我应该澄清。将编辑。
  • 而正是这段代码让我觉得它可能是像 RestSharp 这样的另一个库。
  • 我猜“我正在使用 RestSharpe”的评论可能会增加你的想法@Eser 的分量;)
  • 我没看到。如果我有,我会否决这个;)
【解决方案2】:

如果您使用的是 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; }
}

【讨论】:

  • 我认为这行不通,因此 street-address as street_address
  • @GayanJ 轻松解决,只需更改引号内的字符串。我更新了我的答案,以反映使用破折号而不是下划线的变化。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-11
相关资源
最近更新 更多