在C#中解析JSON数据 [英] Parsing JSON data in C#

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

问题描述

我有一个JSON数据如下:

I have a JSON data as follows

 {"id": "367501354973","from": {
  "name": "Bret Taylor",
  "id": "220439"   }

这是由一个对象(结果)的IDictionary [字符串,对象]

which is returned by an object(result) of IDictionary[String, Object]

在我的C#代码,返回:

In my C# code:

我已经做了的类用于存储JSON值这是如下:

I have made a class for storing the JSON value which is as follows

public class SContent
{
    public string id { get; set; }
    public string from_name { get; set; }
    public string from_id { get; set; }
}

我的存储的解析JSON数据主要的C#功能存储类属性里面的值如下:

List<object> data = (List<object>)result["data"];
            foreach (IDictionary<string, object> content in data)
            {
                SContent s = new SContent();

                    s.id = (string)content["id"];
                    s.from_name = (string)content["from.name"];
                    s.from_id = (string)content["from.id"];

            }

当我执行这个代码,我得到一个例外说的系统找不到钥匙from.name和from.id

When i execute this code, i get an exception saying System cannot find the Key "from.name" and "from.id"

我的评论两行(s.from_name =(串)的含量[from.name]; s.from_id =(串)的含量[from.id];)我的代码运行正常<。 / STRONG>

When i comment the two lines (s.from_name = (string)content["from.name"];s.from_id = (string)content["from.id"];) my code runs fine.

我想我不能够正确地引用嵌套的JSON数据。

任何人都只是验证它,请告诉我如何引用嵌套数据的JSON在C#?

感谢

推荐答案

我不知道你是如何解析JSON字符串。您是否使用了类框架做反序列化?

I'm not sure how you are parsing the JSON string. Are you using a class in the Framework to do the deserialization?

您可以使用在定义的的JavaScriptSerializer System.Web.Script.Serialization 命名空间(您可能需要添加到System.Web.dll程序的引用)

You could use the JavaScriptSerializer Class defined in the System.Web.Script.Serialization Namespace (you may need to add a reference to System.Web.dll)

使用这个类,你会写你这样的代码:

Using that class, you would write your code like this:

public class SContent
{
    public string id { get; set; }
    public SFrom from { get; set; }
}

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



然后反序列化看起来是这样的:

Then deserialization looks like this:

var json = new JavaScriptSerializer();
var result = json.Deserialize<SContent>(/*...json text or stream...*/);

请参阅的的JavaScriptSerializer MSDN上。您可能还需要检查出这种类似的问题

See JavaScriptSerializer on MSDN. You might also want to check out this similar question.

这篇关于在C#中解析JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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