Search code examples
c#asp.net-corexamarinjson.net

How to parse JSON string for List of List of anonymous object which contains List of objects?


I've been trying to deserialize the following JSON string into a model using Newtonsoft's Json library, but failing to do so. The json string is as follows:-

[
    [
        {
            "events": [
                {
                    "d": "Dec 2019 Final",
                    "e": "Released 5 Mar 2020"
                }
            ]
        }
    ],
    [
        {
            "events": [
                {
                    "d": "Some String",
                    "e": "Some Other string"
                }
            ]
        }
    ]
]

I tried doing so by creating its model using Visual Studio internal tool for json to C# (paste special). Also tried creating the models using QuickTypes.io, but so far nothing worked.

The best I can do is parse the api response as List<List<object>> and then manually get the values by iterating its keys & values, which is something I totally want to avoid. Is there a better way to handle this data?


Solution

  • You can use a base model and parse your json:

        public class BaseClass
        {
            public List<EventModel> Events { get; set; }
        }
    
        public class EventModel
        {
            [JsonProperty(PropertyName = "d")]
            public string Date { get; set; }
    
            [JsonProperty(PropertyName = "e")]
            public string Event { get; set; }
        }
    

    And for deserialize json to model use this:

    var model = JsonConvert.DeserializeObject<List<List<BaseClass>>>("your json");