1

I have a json

"1593263898657":{"id":1593263898657,"timeToday":[17,0],"name"= "ABCD"},
"1593263898700":{"id":1593263898700,"timeToday":[17,0],"name"= "ABCD"}"

The class of the json is known to me i.e

public class BaseClass
{
    public long id { get; set; }
    public List<int> timeToday { get; set; }
    public string name { get; set; }
}

public class Root
{
    [JsonProperty("1593263898657")]
    public BaseClass B1 { get; set; }
    [JsonProperty("1593263898700")]
    public BaseClass B2 { get; set; }
}

var myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 

but the problem is while deserializing I don't know how many json property will be there in Root class, so I need to generate the json property dynamically, how can I do that?

Eg: Root class may contain B3,B4... respectively so I do not want to hardcode!

Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49
kush
  • 77
  • 6
  • 6
    I think you are looking for a Dictionary. `Dictionary` ? – Fildor Jul 21 '20 at 07:51
  • You could deserialize the object with JObject.Parse see https://stackoverflow.com/questions/23645034/jobject-parse-vs-jsonconvert-deserializeobject – casenonsensitive Jul 21 '20 at 07:55
  • 1
    @casenonsensitive What benefit would there be in doing so? You'd still have to know in advance, how many BX you'll have. Or restrict yourself to a fix number. Or put them in a Dictionary - where you can also have them deserialized automatically. – Fildor Jul 21 '20 at 07:57
  • 1
    if that's all of your JSON, then it's **invalid**. when including samples of JSON, _please_ take care that your sample is representative and as valid as the full blob. – Franz Gleichmann Jul 21 '20 at 08:12
  • 1
    @Fildor Dictionary solution worked for me Thanks !!. – kush Jul 21 '20 at 09:23

0 Answers0