Question

I am receiving some data in json (I do not have control over how the data is presented).

Can this be deserialized using JsonConvert.DeserializeObject method from the JSON.NET library?

"{'episodes':{'1':true,'2':true,'3':true,'4':true,'5':true,'6':true,'7':true,'8':true,'9':true,'10':true,'11':true,'12':true,'13':true,'14':true,'15':true,'16':true,'17':true,'18':true,'19':true,'20':true,'21':true,'22':true,'23':true,'24':true}}"

I mean, I can't do something like:

public class Episodes {
public bool 1;
public bool 2;
public bool 3;
...
}

Also, this does not work:

public class Episode
{
     [JsonProperty("1")]
    public bool One { get; set; }
     [JsonProperty("2")]
     public bool Two { get; set; }
     [JsonProperty("3")]
     public bool Three { get; set; }
     [JsonProperty("4")]
     public bool Four { get; set; }
     [JsonProperty("5")]
     public bool Five { get; set; }
     [JsonProperty("6")]
     public bool Six { get; set; }
     [JsonProperty("7")]
     public bool Seven { get; set; }
     [JsonProperty("8")]
     public bool Eight { get; set; }
     [JsonProperty("9")]
     public bool Nine { get; set; }
     [JsonProperty("10")]
     public bool Ten { get; set; }
     [JsonProperty("11")]
     public bool Eleven { get; set; }
     [JsonProperty("12")]
     public bool Twelve { get; set; }
     [JsonProperty("13")]
     public bool Thirteen { get; set; }
     ...
}
var result = JsonConvert.DeserializeObject<Episode>(json); // Every property is False

Is there something obvious I am not getting here? I managed to deserialize most of the json I had to deserialize but this one, I can't seem to figure it out.

Thanks a lot, and sorry if this is a dumb question!

Était-ce utile?

La solution

You can deserialize this easily using Json.Net if you define your class correctly.

Define your class like this:

class Wrapper
{
    public Dictionary<int, bool> Episodes { get; set; }
}

Then, deserialize like this (where json is the JSON string from your question):

Wrapper wrapper = JsonConvert.DeserializeObject<Wrapper>(json);

Then you can access the data from the Episodes dictionary in the Wrapper:

foreach (KeyValuePair<int, bool> kvp in wrapper.Episodes)
{
    Console.WriteLine(kvp.Key + " - " + kvp.Value);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top