0

I receive the following kind of response after a JSON request:

{
    participants:{
        "0":{
            "name":"Name1",
            "lastname": "lastname",
            "email":"last@name.com",
            "id":"12345"
        },
        "1":{
            "name":"Name2",
            "lastname": "lastname2",
            "email":"last@name2.de",
            "id":"72382"
        }
    }
}

So far only way I found so far to deserialize this is like this:

using System;
using Newtonsoft.Json;

namespace JSONParse
{
    public class Root
    {
        public object participants { get; set; }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {
            var myJson = JsonConvert.DeserializeObject<Root>(jsonMsg);
            //Do stuff with it
            Console.WriteLine(myJson.participants.ToString());
            Console.ReadLine();
        }

        private static string jsonMsg = @"{
participants:{
    ""0"":{
        ""name"":""Name1"",
        ""lastname"": ""lastname"",
        ""email"":""last@name.de"",
        ""id"":""12345""
        },
    ""1"":{
        ""name"":""Name2"",
        ""lastname"": ""lastname2"",
        ""email"":""last@name2.de"",
        ""id"":""72382""        
       }
    }
}";
    }
}

I've tried parsing it as both an array and a list, but this fails as this object is neither. It looks like a "de-arrayed array", so to speak.

The other, not practical, solution I found would be to create a new class for every possible key inside the response. But since the real data can have a possible unlimited number of keys, this is out of the question. It's not feasible to create an infinite amount of identical classes, all conveniently namend 0 to infinity.

How can I parse this response, so I can access the information correctly from within my code?

waka
  • 3,362
  • 9
  • 35
  • 54
  • 2
    For `participants` use a `Dictionary` or `Dictionary` as shown in as shown in [How can I parse a JSON string that would cause illegal C# identifiers?](https://stackoverflow.com/a/24536564/3744182) or [Create a strongly typed c# object from json object with ID as the name](https://stackoverflow.com/a/34213724/3744182). – dbc Mar 16 '22 at 18:50
  • 1
    If you really need that JSON object to be deserialized as a `List` instead of a dictionary, you could use a custom converter as shown in [Display JSON object array in datagridview](https://stackoverflow.com/a/41559688/3744182). – dbc Mar 16 '22 at 18:57
  • 1
    @dbc Thanks for pointing me in the right direction, I was finally able to solve the problem. :) – waka Mar 18 '22 at 10:06

0 Answers0