Reputation: 2107
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": "[email protected]"
},
"767": {
"contact_id": "767",
"real_name": "Peter File",
"telephone": "02580845866",
"email": "[email protected]"
}
}
}
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; }
}
Upvotes: 0
Views: 58
Reputation: 38468
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();
Upvotes: 2