0

I have a JSON like

{
    "myObject":{
        "Difficult": true,
        "Impossible": false
    }
}

and a model like

public class Blas
{
    public string something { get; set; }
    public int somethinElse { get; set; }
    public Dictionary<string, bool> myObject{ get; set; } //this is how I'm currently modeling the JSON
}

and when I use it I'm doing myObject["Difficult"]; but I need to do something like if(myObject.Difficult)..

Note to duplicate suggestion: The suggestion is irrelevant because as the title says, my question is regarding to model a JSON in C#, not converting. I can convert, but I need to improve my current modeling in c#.

user33276346
  • 1,501
  • 1
  • 19
  • 38
  • You need to parse your JSON into your model (or deserialize it to your model). Where from is the JSON coming into your C# code? – Racil Hilan Oct 24 '19 at 04:56
  • Possible duplicate of [Convert JSON String To C# Object](https://stackoverflow.com/questions/4611031/convert-json-string-to-c-sharp-object) – Ravi Oct 24 '19 at 04:59

1 Answers1

0

add class "MyObject" like this

Import

using Newtonsoft.Json

Code

public class MyObject
{
    [JsonProperty("Difficult")]
    public bool Difficult { get; set; }
    [JsonProperty("Impossible")]
    public bool Impossible { get; set; }
}

public class MyData {
    [JsonProperty("myObject")]
    public MyObject { get; set; }
}

then, define class like this

MyData obj = JsonConvert.DeserializeObject<MyData>(jsonString);

jsonString would be your json string.

Arphile
  • 841
  • 6
  • 18
  • I recently learned about interfaces, could I introduce an interface here or there? would it improve my code? – user33276346 Oct 24 '19 at 05:09
  • You can also remove the [JsonProperty] attributes if they are the same name and by convention it will auto map to that property. – Ryan Dobbs Oct 24 '19 at 05:13
  • @user33276346 I've always found it better to leave them in for clarity. Personal choice though. – RoadRunner Oct 24 '19 at 05:15