0

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?

dbc
  • 104,963
  • 20
  • 228
  • 340
whoami
  • 1,689
  • 3
  • 22
  • 45
  • 1
    You're ignoring the first level. The code you have is assuming that the accountType is top level which would look like `{"accountType":"New"}`. You'll need to make a new class with a property of type `Data` named `data`. Fun fact, in Visual Studio, if you copy the raw JSON and go to `Edit > Paste Special > Paste JSON As Classes` it will create the structure for you. – Jesse Jan 25 '22 at 23:52

1 Answers1

1

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);
Serge
  • 40,935
  • 4
  • 18
  • 45