c# - Exclude items during deserialization if a specific attribute doesn't exist -


i have json string can contain multiple students , teachers. example shown below. want deserialize json separate lists based on whether contains particular attribute.

[   {     "school": "st.xavier"   },   {     "teacherid": 1,     "name": "prof.xavier",     "position": "professor",     "class": "elite"   },   {     "studentid": 1,     "name": "quicksilver",     "ability": "rush",     "class": "elite"   } ] 

for example:

list<teacher> teacherlist = jsonconvert.deserialize<teacher>(json); list<student> studentlist = jsonconvert.deserialize<student>(json); 

during deserialization, school info ignored, , each list contain items attributes matching according class. teacherlist contain teacher info, , studentlist contain student info.

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

how can this?

you can make simple helper method want:

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

then use this:

list<teacher> teachers = deserialize<teacher>(json, "teacherid"); list<student> students = deserialize<student>(json, "studentid"); 

fiddle: https://dotnetfiddle.net/axq99x


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -