1

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?

dbc
  • 104,963
  • 20
  • 228
  • 340
d00d
  • 688
  • 1
  • 8
  • 29
  • You could deserialize to an anonymous type `new { data = default(List) }` then access the `data` property as shown in [How can I deserialize some subtree only](https://stackoverflow.com/a/67319571/3744182). – dbc Jun 09 '22 at 22:38

1 Answers1

5

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

Guru Stron
  • 102,774
  • 10
  • 95
  • 132