Search code examples
c#jsonjson-deserialization

Having trouble Deserialize a jason of objects array


{
    "-NL5BmYke6OAh580HEbF": {
        "Adress": "test",
        "ID": "test",
        "Namn": "test",
        "TelefonNummer": "test"
    },
    "-NL5Bncq0GgwLerFXS-v": {
        "Adress": "test1",
        "ID": "test1",
        "Namn": "test1",
        "TelefonNummer": "test1"
    }
}

This is the json but i have unique key numbers before the values i want to get and those are giving trouble accessing the json string inside.

var strings = new JavaScriptSerializer().Deserialize<List<string>>(s);

This is what im trying right now to get the invudual strings then too deserialize again but it doesnt work.

Anyone know a solution for this?


Solution

  • You can deserialize your input as Dictionary<string, Person> (see the example below). The unique keys from your input will become keys in the result dictionary accessible via deserialized.Keys.

    
    //define class that will serve as Type for values in your dictionary
    public class Person
    {
        public string ID { get; set; }
        public string Namn { get; set; }
        public string TelefonNummer { get; set; }
        public string Adress { get; set; }
    }
    
    //...
    
    var json = "... your input here";
    
    var deserialized = new JavaScriptSerializer().Deserialize<Dictionary<string, Person>>(json);
    
    

    You can then further iterate through the dictionary and set the Key as ID for example:

    var persons = deserialized.Select(kvp =>
    {
        var person = kvp.Value;
        person.ID = kvp.Key; // or add another property for this value
        return person;
    });