Home > front end >  C# Deserialize a Serialized JSON string
C# Deserialize a Serialized JSON string

Time:11-17

This is the JSON string which I received

{ 

"Date":"2021-11-16",

"Name":"Raj",

"BError":{

"code":"errorcode",

"details":"message"

},

"AStatus":true

}

I have to Deserialize the above JSON string

I have given the class details with JSON annotations below

public class Demo
{
[JsonProperty("Date")]
public DateTime? Date{ get; set; }

pulic string Name{get;set;}

[JsonProperty("B-Error")]
public BError BError{ get; set; }

[JsonProperty("A-Status")]
public bool AStatus { get; set; }
}

public class BError
{
public string code { get; set; }
public string details { get; set; }
}

the code I have written to Deserialize is

var responseJson = JsonConvert.DeserializeObject(input_JSON_string).ToString();
Demo d = JsonConvert.DeserializeObject<Demo>(responseJson);

this code is converting input_JSON_string into object but not all fields. The fields "Date" and "Name" is converting but the fields "B-Error" and "A-Status" is storing values as NULL.

How to Deserialize all the fields?

CodePudding user response:

This is supposed to be the name of the property in the json

[JsonProperty("B-Error")]

"B-Error" is not the name of the property in your json; your json property is called "BError" - you seem to have a similar typo on A-Status

Do this, and everything will work:

[JsonProperty("BError")]

JsonProperty allows you to have C# properties that are called one thing, that connect to a json property called another thing. It means you can maintain c# naming conventions for your c# properties (you should rename your c# property code to Code) even though the json isn't named like c# would be

To get a full set of working classes together with hints about how to deserialize, just paste your json into https://QuickType.io

CodePudding user response:

you can add a constructor if you want it the way you want

public partial class Demo
{
    [JsonProperty("Date")]
    public DateTimeOffset Date { get; set; }

    [JsonProperty("Name")]
    public string Name { get; set; }

    [JsonProperty("B-Error")]
    public BError BError { get; set; }

    [JsonProperty("A-Status")]
    public bool AStatus { get; set; }
    
    [JsonConstructor]
    public Demo(DateTimeOffset Date,string Name, BError BError, bool AStatus)
    {
        this.Date=Date;
        this.Name=Name;
        this.BError=BError;
        this.AStatus=AStatus;
    }
}
public partial class BError
{
    [JsonProperty("code")]
    public string Code { get; set; }

    [JsonProperty("details")]
    public string Details { get; set; }
}

this json was tested and code is working properly

{
   "Date":"2021-11-16",
   "Name":"Raj",
   "BError":{
      "code":"errorcode",
      "details":"message"
   },
   "AStatus":true
}
  • Related