Deserializing JSON array into strongly typed .NET object
This solution seems to work for me and gets around having to code a bunch of classes with "Data" in them.
public interface IDataResponse<T> where T : class
{
List<T> Data { get; set; }
}
public class DataResponse<T> : IDataResponse<T> where T : class
{
[JsonProperty("data")]
public List<T> Data { get; set; }
}
I should have included this to begin with, here is an example method using the above:
public List<TheUser> GetUser()
{
var results = GetUserJson();
var userList = JsonConvert.DeserializeObject<DataResponse<TheUser>>(results.ToString());
return userList.Data.ToList();
}
Afer looking at the source, for WP7 Hammock doesn't actually use Json.Net for JSON parsing. Instead it uses it's own parser which doesn't cope with custom types very well.
If using Json.Net directly it is possible to deserialize to a strongly typed collection inside a wrapper object.
var response = @"
{
""data"": [
{
""name"": ""A Jones"",
""id"": ""500015763""
},
{
""name"": ""B Smith"",
""id"": ""504986213""
},
{
""name"": ""C Brown"",
""id"": ""509034361""
}
]
}
";
var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass));
return des.data.Count.ToString();
and with:
public class MyClass
{
public List<User> data { get; set; }
}
public class User
{
public string name { get; set; }
public string id { get; set; }
}
Having to create the extra object with the data property is annoying but that's a consequence of the way the JSON formatted object is constructed.
Documentation: Serializing and Deserializing JSON
try
List<TheUser> friends = jsonSerializer.Deserialize<List<TheUser>>(response);
This worked for me for deserializing JSON into an array of objects:
List<TheUser> friends = JsonConvert.DeserializeObject<List<TheUser>>(response);