Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JsonConvert.DeserializeObject return null value

I did search but seem like i didnt find any solution for this… This is my sample Json:

{
  "WSettings":{
  "Message":"\"We are the universe's way of experiencing itself.\"<br/>- Kurzgesagt -",
  "universalMessageProcChance":10,
  "Hi":{
         "altName":"Hi",
         "normalState":"hi",
         "hState":"hi_h",
         "aState":"hi_a",
         "background":"bg_owo_r",
         "stateLayout":4,
         "backgroundLayout":1,
         "eventMessage":"Da"
     },
  "Yu":{
         "altName":"Al",
         "normalState":"al",
         "hState":"al_h",
         "aState":"ali_a",
         "background":"bg_owo_b",
         "stateLayout":4,
         "backgroundLayout":1,
         "eventMessage":"Da"
    }
  }
}

This is my classes:

public class WSettings
{
    public string Message { get; set; }
    public int universalMessageProcChance { get; set; }

    [JsonProperty("Hi")]
    public StateW Hi { get; set; }

    [JsonProperty("Yu")]
    public StateW Yu { get; set; }
}

public class StateW
{
    public string altName { get; set; }
    public string normalState { get; set; }
    public string hState { get; set; }
    public string aState { get; set; }
    public string background { get; set; }
    public int stateLayout { get; set; }
    public int backgroundLayout { get; set; }
    public string eventMessage { get; set; }
}

and this to deserialize:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var w = Newtonsoft.Json.JsonConvert.DeserializeObject<WSettings>(File.ReadAllText(@"json.txt"));

It returns all attributes as null. I honestly dont know what is wrong there so please pardon my ignorant. Any help is appericated 🙂

>Solution :

You’ll need another wrapper class on WSettings.
Try something like this:

public class WSettingsParent
{
    public WSettings WSettings { get; set; }
}

And deserialize like this:

WSettingsParent myDeserializedClass = JsonConvert.DeserializeObject<WSettingsParent>(File.ReadAllText(@"json.txt")));

Here’s a useful tool for checking that you can use to make sure the structure of your classes are properly set:
https://json2csharp.com/
Just paste your json on the left side and it will generate classes accordingly. (You might need some slight modifications but the big picture is visible there).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading