Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to ignore/unwrap object name when deserializing from JSON?

I am trying to deserialize JSON that i receive from a webservice. The JSON looks like that:

{ "data": 
   [  
      {"name": "john", "company": "microsoft"}, 
      {"name": "karl", "company":"google"}
   ]
}

My model which i want to deserialize into:

public class employee {
   public string name {get; set;}
   public string company {get; set;}

}

The problem is, that i cannot deserialize using System.Text.Json because of that object name "data". How can i make the deserializer to unwrap / ignore the data tag and just start from whatever is inside that tag?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just create a wrapper object and use it for deserialization:

public class Root {
   public List<employee> data {get; set;}
}

var employees = JsonSerializer.Deserialize<Root>(jsonString).data;

In case there a lot of different types contains this pattern you can make Root generic:

public class Root<T> {
   public List<T> data {get; set;}
}

var employees = JsonSerializer.Deserialize<Root<employee>>(jsonString).data;

Note that data contains a collection of employees not a single record.

Also note that you can use recommended Pascal casing for property names, deserializer should be able to pick it up.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading