【问题标题】:How to deserialize json property to class property?如何将 json 属性反序列化为类属性?
【发布时间】:2017-07-14 05:09:49
【问题描述】:

我的 JSON 文件

    [
      {
        "amount":"1000000.0",
        "check_number":1,
        "payment_number":5,
        "attachments":[
          {
            "id":5324,
            "url":"http://www.example.com/",
            "filename":"january_receipt_copy.jpg"
          }
        ]
      }
    ]

我的班级档案

public class Attachment
{
    public int id { get; set; }
    public string url { get; set; }
    public string filename { get; set; }
}

public class AccountDetail
{
    public string amount { get; set; }
    public int check_number { get; set; }
    public int payment_number { get; set; }
}

public class RootObject
{
    public AccountDetail accountdetail{ get; set; }
    public List<Attachment> attachments { get; set; }
}

现在我想映射 JSON 文件的属性 'check_number','amount'accountdetail 使用 newtonsoft JSON 反序列化。

【问题讨论】:

  • 显示您尝试过的代码并告诉我们出了什么问题?
  • @un-lucky:var listRootObject= JsonConvert.DeserializeObject>(response.ToS‌​tring());这里我的响应等于上面显示的 json 文件。当我访问 listRootObject.accountdetail 时给出 null 但我想将 accountdetail 属性与 json 文件 'check_number','amount' 属性映射。

标签: c# json json.net json-deserialization


【解决方案1】:

你需要以下两个类:

public class Attachment
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("url")]
    public string Url { get; set; }

    [JsonProperty("filename")]
    public string Filename { get; set; }
}

public class AccountDetails
{
    [JsonProperty("amount")]
    public string Amount { get; set; }

    [JsonProperty("check_number")]
    public int CheckNumber { get; set; }

    [JsonProperty("payment_number")]
    public int PaymentNumber { get; set; }

    [JsonProperty("attachments")]
    public IList<Attachment> Attachments { get; set; }
}

通过定义上述类,您可以反序列化您的 json,如下所示:

var accountsDetails = JsonConvert.DeserializeObject<IEnumerable<AccountDetails>>(json);

【讨论】:

  • var listRootObject= JsonConvert.DeserializeObject>(response.ToS‌​‌​tring());这里我的响应等于上面显示的 json 文件。当我访问 listRootObject.accountdetail 时给出 null 但我想将 accountdetail 属性与 json 文件 'check_number','amount' 属性映射。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-19
  • 1970-01-01
  • 2014-01-24
  • 2012-08-19
  • 2013-04-09
  • 2020-01-25
相关资源
最近更新 更多