How can Deserialize with Javascript Serializer? (ASP.net)
public class SocialFriends
{
public string id { get; set; }
public string name { get; set; }
}
this is my Class.
List<SocialFriends> oList2 = ser.Deserialize<List<SocialFriends&开发者_如何学Cgt;>(response.Content);
I'm getting data's like this. But it returns 0 data :S
Data is here
{"data":[{"name":"George","id":"511222445"},{"name":"Mayk","id":"517247768"}]}
I can't explain this problem? Can anybody say, where is my fault?
Create a class
class Data
{
public SocialFriends[] data { get; set; }
}
and change your code to:
Data oList2 = ser.Deserialize<Data>(response.Content);
This code works.
public class SocialFriendsData
{
public List<SocialFriends> Data { get; set; }
}
public class SocialFriends
{
public string id { get; set; }
public string name { get; set; }
}
Deserialization:
JavaScriptSerializer ser = new JavaScriptSerializer();
string response = "{\"data\":[{\"name\":\"George\",\"id\":\"511222445\"},{\"name\":\"Mayk\",\"id\":\"517247768\"}]}";
SocialFriendsData oList2 = ser.Deserialize<SocialFriendsData>(response);
Your JSON is wrapped in a data
property. You'll have to grab the JSON string out of that data
property. I don't know which JSON serializer you use, but based on what you provided, the easiest way is probably just to create an intermediate DataHolder
class:
public class DataHolder
{
public string Data { get; set; }
}
Then deserialize it like this:
var dataHolder = ser.Deserialize<DataHolder>(response.Content);
var oList2 = ser.Deserialize<List<SocialFriends>>(dataHolder.Data);
If you're using a robust JSON serializer like Json.NET, you can even skip the intermediate deserialization and change your DataHolder type to the correct type:
public class DataHolder
{
public List<SocialFriends> SocialFriends { get; set; }
}
And then use this code to get the data:
var dataHolder = ser.Deserialize<DataHolder>(response.Content);
var oList2 = dataHolder.SocialFriends;
精彩评论