Home > front end >  How to ignore/unwrap object name when deserializing from JSON?
How to ignore/unwrap object name when deserializing from JSON?

Time:06-07

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?

CodePudding user response:

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 (of it it does not - you can help it by providing JsonSerializerOptions with correct PropertyNamingPolicy set).

  • Related