Json.NET 单个对象Json字符串反序列成两个不同实体对象

本文主要介绍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>>(json);
var patients = JsonConvert.DeserializeObject<List<Patient>>(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);
}
相关推荐
lzhdim1 小时前
C# 通过 Windows API 实现进程内存读写操作
开发语言·windows·c#
-银雾鸢尾-1 小时前
C#中的预处理指令
开发语言·c#
dalong101 小时前
Savitzky-Golay 的C# 实现
开发语言·kotlin·c#
烟锁池塘柳01 小时前
Conda 创建环境报错:Unable to read repodata JSON file,清华源 pkgs/free 失效解决方法
json·conda
猿长大人1 小时前
C# | Autofac 新手指南:从零理解依赖注入与组件装配
c#·.net·di·依赖注入
show4332 小时前
多格式导出怎么做?2026免费小程序TXT/SRT实践
开发语言·小程序·c#
czhaii2 小时前
word插入表格排版创建或编辑应用技巧
ui·c#·xhtml
在世修行3 小时前
从零打造 C# 工业视觉检测系统(十一):Task 异步编程与实时性保障
开发语言·c#·task异步
czhc11400756633 小时前
2026-08-09 学习笔记:背钻检测核心概念
c#
yanaiding15 小时前
C# WPF 独立开发看图工具 PixSight 经验介绍(二)—— 水印模块开发实录
图像处理·c#·wpf·个人开发