我试图反序列化一个Facebook朋友的图形API调用到一个对象列表。JSON对象看起来像:
{"data":[{"id":"518523721","name":"ftyft"},
{"id":"527032438","name":"ftyftyf"},
{"id":"527572047","name":"ftgft"},
{"id":"531141884","name":"ftftft"},
{"id":"532652067","name"...
List<EFacebook> facebooks = new JavaScriptSerializer().Deserialize<List<EFacebook>>(result);
它不起作用,因为原始对象无效。我怎么反序列化这个?
你需要创建一个这样的结构:
public class Friends
{
public List<FacebookFriend> data {get; set;}
}
public class FacebookFriend
{
public string id {get; set;}
public string name {get; set;}
}
那么你应该能够做到:
Friends facebookFriends = new JavaScriptSerializer().Deserialize<Friends>(result);
我的类名只是一个例子。你应该使用专有名词。
添加一个示例测试:
string json =
@"{""data"":[{""id"":""518523721"",""name"":""ftyft""}, {""id"":""527032438"",""name"":""ftyftyf""}, {""id"":""527572047"",""name"":""ftgft""}, {""id"":""531141884"",""name"":""ftftft""}]}";
Friends facebookFriends = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Friends>(json);
foreach(var item in facebookFriends.data)
{
Console.WriteLine("id: {0}, name: {1}", item.id, item.name);
}
生产:
id: 518523721, name: ftyft
id: 527032438, name: ftyftyf
id: 527572047, name: ftgft
id: 531141884, name: ftftft
如果你使用的是。net Core 3.0,你可以使用System.Text.Json(现在是内置的)来反序列化JSON。
第一步是创建类来对JSON建模。有很多工具可以帮助解决这个问题,这里列出了一些答案。
一些选项是http://json2csharp.com, http://app.quicktype.io或使用Visual Studio(菜单编辑→粘贴特殊→将JSON粘贴为类)。
public class Person
{
public string Id { get; set; }
public string Name { get; set; }
}
public class Response
{
public List<Person> Data { get; set; }
}
然后你可以使用以下方法反序列化:
var people = JsonSerializer.Deserialize<Response>(json);
如果你需要添加设置,比如camelCase处理,然后像这样将序列化器设置传递给反序列化器:
var options = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
var person = JsonSerializer.Deserialize<Response>(json, options);
有时候我更喜欢动态对象:
public JsonResult GetJson()
{
string res;
WebClient client = new WebClient();
// Download string
string value = client.DownloadString("https://api.instagram.com/v1/users/000000000/media/recent/?client_id=clientId");
// Write values
res = value;
dynamic dyn = JsonConvert.DeserializeObject(res);
var lstInstagramObjects = new List<InstagramModel>();
foreach(var obj in dyn.data)
{
lstInstagramObjects.Add(new InstagramModel()
{
Link = (obj.link != null) ? obj.link.ToString() : "",
VideoUrl = (obj.videos != null) ? obj.videos.standard_resolution.url.ToString() : "",
CommentsCount = int.Parse(obj.comments.count.ToString()),
LikesCount = int.Parse(obj.likes.count.ToString()),
CreatedTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds((double.Parse(obj.created_time.ToString()))),
ImageUrl = (obj.images != null) ? obj.images.standard_resolution.url.ToString() : "",
User = new InstagramModel.UserAccount()
{
username = obj.user.username,
website = obj.user.website,
profile_picture = obj.user.profile_picture,
full_name = obj.user.full_name,
bio = obj.user.bio,
id = obj.user.id
}
});
}
return Json(lstInstagramObjects, JsonRequestBehavior.AllowGet);
}