Deserialize JSON to 2 different models

前端 未结 9 1359
眼角桃花
眼角桃花 2021-02-06 23:42

Does Newtonsoft.JSON library have a simple way I can automatically deserialize JSON into 2 different Models/classes?

For example I get the JSON:

[{
  \"g         


        
9条回答
  •  無奈伤痛
    2021-02-07 00:10

    It you want to do it with 1 call, you need to create a class that matches the JSON. That class can then return Guardian and Patient objects as needed. Also you'll need to use an array or list for the return type because the source JSON is an array.

    The class to create:

    public class Pair
    {
        public Pair()
        {
            Guardian = new Guardian();
            Patient = new Patient();
        }
    
        [JsonIgnore]
        public Guardian Guardian { get; set; }
    
        [JsonIgnore]
        public Patient Patient { get; set; }
    
        [JsonProperty(PropertyName = "guardian_id")]
        public int GuardianID
        {
            get { return Guardian.ID; }
            set { Guardian.ID = value; }
        }
    
        [JsonProperty(PropertyName = "guardian_name")]
        public string GuardianName
        {
            get { return Guardian.Name; }
            set { Guardian.Name = value; }
        }
    
        [JsonProperty(PropertyName = "patient_id")]
        public int PatientID
        {
            get { return Patient.ID; }
            set { Patient.ID = value; }
        }
    
        [JsonProperty(PropertyName = "patient_name")]
        public string PatientName
        {
            get { return Patient.Name; }
            set { Patient.Name = value; }
        }
    }
    

    And how to use it:

    var pairs = JsonConvert.DeserializeObject(response.Content);
    
    if (pairs.Any())
    {
        var pair = pairs[0];
        Console.WriteLine(pair.Guardian.Name);
        Console.WriteLine(pair.Patient.Name);
    }
    

提交回复
热议问题