Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
651 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...