如何将json属性反序列化为类属性?

时间:2017-07-14 05:09:49

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

我的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文件的属性&#39; check_number&#39;,&#39; amount&#39; 等   通过使用newtonsoft JSON反序列化来 accountdetail

1 个答案:

答案 0 :(得分:2)

您需要以下两个类:

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