反序列化JSON用C# [英] Deserialize JSON with C#

查看:277
本文介绍了反序列化JSON用C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图反序列化的Facebook好友图形API调用到对象的列表。 JSON对象是这样的:

I'm trying to deserialize a Facebook friends graph API call into a list of objects. The JSON object looks like:

{"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);

它不工作,因为原始的对象是无效的。结果
我该如何反序列化呢?

It's not working because the primitive object is invalid.
How can I deserialize this?

推荐答案

您需要创建一个结构是这样的:

You need to create a structure like this:

public class Friends
{

    public List<FacebookFriend> data {get;set;}
}

public class FacebookFriend
{

    public string id {get;set;}
    public string name {get;set;}
}

那么你应该能够做到:

Then you should be able to do:

Friends facebookFriends = new JavaScriptSerializer().Deserialize<Friends>(result);

我的班的名称只是一个例子。您应该使用合适的名字。

Names of my classes are just an example. You should use proper names.

添加样品测试:

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

这篇关于反序列化JSON用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆