如果特定属性不存在,则在反序列化期间排除项目

时间:2016-08-29 10:08:53

标签: c# json json.net deserialization

我有一个JSON字符串,可以包含多个学生和教师。一个例子如下所示。我想根据它是否包含特定属性将JSON反序列化为单独的列表。

[
  {
    "School": "St.Xavier"
  },
  {
    "teacherid": 1,
    "name": "Prof.Xavier",
    "position": "Professor",
    "class": "elite"
  },
  {
    "studentid": 1,
    "name": "QuickSilver",
    "ability": "Rush",
    "class": "elite"
  }
]

例如:

List<Teacher> teacherList = JsonConvert.Deserialize<Teacher>(json);
List<Student> studentList = JsonConvert.Deserialize<Student>(json);

在反序列化期间,学校信息将被忽略,每个列表将仅包含具有根据类别匹配的属性的项目。因此teacherList仅包含教师信息,而studentList仅包含学生信息。

public class Teacher
{
    [JsonProperty("teacherid")]
    public string TeacherID {get;set;}

    [JsonProperty("name")]
    public string Name {get;set;}

    [JsonProperty("position")]
    public string Position {get;set;}

    [JsonProperty("class")]
    public string InCharge {get;set;}
}

public class Student
{
    [JsonProperty("studentid")]
    public string StudentID {get;set;}

    [JsonProperty("name")]
    public string Name {get;set;}

    [JsonProperty("ability")]
    public string Ability {get;set;}

    [JsonProperty("class")]
    public string Enrolled {get;set;}
}

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以制作一个简单的辅助方法来执行您想要的操作:

public static List<T> Deserialize<T>(string json, string attribute)
{
    return JArray.Parse(json)
                 .Children<JObject>()
                 .Where(jo => jo[attribute] != null)
                 .Select(jo => jo.ToObject<T>())
                 .ToList();
}

然后像这样使用它:

List<Teacher> teachers = Deserialize<Teacher>(json, "teacherid");
List<Student> students = Deserialize<Student>(json, "studentid");

小提琴:enter image description here