简体   繁体   中英

Deserializing JSON object to array or list

I'm still not entirely sure on what exactly to ask, so apologies if this is ill conceived. The other questions I have found are related to people already receiving object arrays in JSON.

My JSON string is returning from a third party as an object when I have only ever dealt with it being returned as an array which is easily converted into objects in the past.

var success = JsonConvert.DeserializeObject<RootObjectClass>(result); gives me a `Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`

Should I convert this to an array, and if so how, as the objects are individually named the same as the property "contact_id" value?

Else, could someone point me in the right direction of best practice of how to get a list of Contacts out of this JSON.

The JSON structure is shown below.

{
    "status": true,
    "error_code": "",
    "error_message": "",
    "data": {
        "693": { // Contact obj, always the same as contact_id
            "contact_id": "693",
            // removed lots of properties for brevity
            "real_name": "Mike Hunt",
            "telephone": "01280845867",
            "email": "mhunt@test.com"
        },
        "767": { 
            "contact_id": "767",
            "real_name": "Peter File",
            "telephone": "02580845866",
            "email": "pfile@test.com"
        }
    }
}

Class structure

[Serializable()]
[DataContract]
public class RootObjectClass
{
    [DataMember()]
    public bool status { get; set; }
    [DataMember()]
    public string error_code { get; set; }
    [DataMember()]
    public string error_message { get; set; }
    [DataMember()]
    public DataClass data { get; set; }
}
[Serializable()]
[DataContract]
public class DataClass
{
    [DataMember]
    public Contact contact { get; set; }
}

You can deserialize data property to a dictionary :

[Serializable()]
[DataContract]
public class RootObjectClass
{
    [DataMember()]
    public bool status { get; set; }
    [DataMember()]
    public string error_code { get; set; }
    [DataMember()]
    public string error_message { get; set; }
    [DataMember()]
    public Dictionary<string,Contact> data { get; set; }
}

Then you can select the contacts like this:

var contacts = rootObject.data.Values.ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM