Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

c# - How to deserialize json property to class property?

My JSON file

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

My Class File

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

Now I want to map JSON file's properties 'check_number','amount' etc to accountdetail by using newtonsoft JSON deserialization.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need the following two classes:

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

By defining the above classes you can deserialize your json as below:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...