将JSON反序列化为2种不同的模型 [英] Deserialize JSON to 2 different models

查看:42
本文介绍了将JSON反序列化为2种不同的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Newtonsoft.JSON库是否有一种简单的方法,我可以将JSON自动反序列化为2个不同的Models/classes?

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

例如,我得到JSON:

For example I get the JSON:

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

我需要将此序列反序列化为以下模型:

And I need de-serialize this to the following models:

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

是否有一种简单的方法可以将此JSON反序列化为2个模型,而不必遍历JSON?也许JSON属性ID会起作用?

Is there a simple way to deserialize this JSON into 2 Models without having to iterate over the JSON? Maybe JSON property ids will just work?

Pair<Guardian, Patient> pair = JsonConvert.DeserializeObject(response.Content);

推荐答案

首先,您的模型略有错误.名称属性必须是字符串,而不是整数:

First off, your models are slightly incorrect. The name properties need to be strings, instead of integers:

class Guardian
{

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

    [JsonProperty(PropertyName = "guardian_name")]
    public string Name { get; set; }            // <-- This
}


class Patient
{

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

    [JsonProperty(PropertyName = "patient_name")]
    public string Name { get; set; }            // <-- This
}

更正该错误之后,您可以将JSON字符串反序列化为两个不同类型的列表.就您而言,分别是List<Guardian>List<Patient>:

Once you've corrected that, you can deserialize the JSON string into two lists of different types. In your case, List<Guardian> and List<Patient> respectively:

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

这篇关于将JSON反序列化为2种不同的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆