Search code examples
c#json.net-corejson-deserializationsystem.text.json

json is parsed as null


I have a json structure like below.

{"data":{"accountType":"New"}}

The model for this is as follows.

 public class Data
 {
     public string accountType { get; set; }
 }

Below is how I am parsing this data using System.Text.Json.

string json2 = "{\"data\":{\"accountType\":\"New\"}}\n";
var account = JsonSerializer.Deserialize<Data>(json2);

but account is parsed as null. What am I doing wrong here?


Solution

  • you need a root class

    public class Root
     {
         public Data data { get; set; }
     }
    public class Data
     {
         public string accountType { get; set; }
     }
    

    and code

    var account = JsonSerializer.Deserialize<Root>(json2);