[Solved] Parsing Array of objects JSON in C#


Your json is invalid…here is correct json

   {
    "status": {
        "success": [{
                "User": {
                    "id": "1377",
                    "username": "Dr.Hema Sathish"
                },
                "Speciality": {
                    "id": "2",
                    "name": "Dermatology(Skin Specialist)"
                }
            },
            {
                "User": {
                    "id": "1390",
                    "username": "Dr.Nichita Balaji"
                },
                "Speciality": {
                    "id": "2",
                    "name": "Dermatology(Skin Specialist)"
                }

            }
        ]
    }
   }

You can create below classes to deserialize it using Newtonsoft

public class User
{
    public string id { get; set; }
    public string username { get; set; }
}

public class Speciality
{
    public string id { get; set; }
    public string name { get; set; }
}

public class Success
{
    public User User { get; set; }
    public Speciality Speciality { get; set; }
}

public class Status
{
    public List<Success> success { get; set; }
}

public class RootObject
{
    public Status status { get; set; }
}

Here is the code to deserialize it

    string json =
        "   {\r\n   \t\"status\": {\r\n   \t\t\"success\": [{\r\n   \t\t\t\t\"User\": {\r\n   \t\t\t\t\t\"id\": \"1377\",\r\n   \t\t\t\t\t\"username\": \"Dr.Hema Sathish\"\r\n   \t\t\t\t},\r\n   \t\t\t\t\"Speciality\": {\r\n   \t\t\t\t\t\"id\": \"2\",\r\n   \t\t\t\t\t\"name\": \"Dermatology(Skin Specialist)\"\r\n   \t\t\t\t}\r\n   \t\t\t},\r\n   \t\t\t{\r\n   \t\t\t\t\"User\": {\r\n   \t\t\t\t\t\"id\": \"1390\",\r\n   \t\t\t\t\t\"username\": \"Dr.Nichita Balaji\"\r\n   \t\t\t\t},\r\n   \t\t\t\t\"Speciality\": {\r\n   \t\t\t\t\t\"id\": \"2\",\r\n   \t\t\t\t\t\"name\": \"Dermatology(Skin Specialist)\"\r\n   \t\t\t\t}\r\n\r\n   \t\t\t}\r\n   \t\t]\r\n   \t}\r\n   }";
    RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(json);
    var successes = rootObject.status.success;
    var specialityObjects = successes.Select(success => success.Speciality).ToList();
    var users = successes.Select(success => success.User).ToList();
    Console.WriteLine(users[0].id + " " + users[0].username);
    Console.WriteLine(users[1].id + " " + users[1].username);
    Console.WriteLine(specialityObjects[0].id + " " + specialityObjects[0].name);
    Console.WriteLine(specialityObjects[1].id + " " + specialityObjects[1].name);
    Console.ReadLine();

//OUTPUT

1377 Dr.Hema Sathish
1390 Dr.Nichita Balaji
2 Dermatology(Skin Specialist)
2 Dermatology(Skin Specialist)

6

solved Parsing Array of objects JSON in C#