本文主要介绍Newtonsoft.JSON(Json.NET)中,将一个对象的Json字符串反序化成两个不同实体对象的方法代码。具体效果如下

Json字符串

[{
  "guardian_id": "1453",
  "guardian_name": "Foo Bar",
  "patient_id": "938",
  "patient_name": "Foo Bar",
}]

序列化成的两个Model实例对象

class Guardian {
  [JsonProperty(PropertyName = "guardian_id")]
  public int ID { get; set; }
  [JsonProperty(PropertyName = "guardian_name")]
  public int Name { get; set; }
}

class Patient {
  [JsonProperty(PropertyName = "patient_id")]
  public int ID { get; set; }
  [JsonProperty(PropertyName = "patient_name")]
  public int Name { get; set; }
}

1、分别反序化成实体(model)对象

string json = @"[{'guardian_id':'1453','guardian_name':'Foo Bar','patient_id':'938','patient_name':'Foo Bar'}]";
var guardians = JsonConvert.DeserializeObject<List<Guardian&gt;&gt;(json);
var patients = JsonConvert.DeserializeObject<List<Patient&gt;&gt;(json);

2、通过Pair类反序化

反序化一次可以实现

Pair如下

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

序列化代码

string json = @"[{'guardian_id':'1453','guardian_name':'Foo Bar','patient_id':'938','patient_name':'Foo Bar'}]";
var pairs = JsonConvert.DeserializeObject<Pair[]>(json);
if (pairs.Any())
{
    var pair = pairs[0];
    Console.WriteLine(pair.Guardian.Name);
    Console.WriteLine(pair.Patient.Name);
}

原文地址:https://blog.csdn.net/lwf3115841/article/details/134796689

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_46214.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注