Csharp/C#教程:在C#中解析JSON数据分享


在C#中解析JSON数据

我有一个JSON数据如下

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

由IDictionary [String,Object]的对象(结果)返回

在我的C#代码中:

我已经创建了一个用于存储JSON值类,如下所示

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

我的主要C#函数存储解析JSON数据并将值存储在类属性中,如下所示:

 List data = (List)result["data"]; foreach (IDictionary 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"]; } 

当我执行此代码时,我得到一个exception,说系统无法找到密钥“from.name”和“from.id”

当我评论两行(s.from_name =(string)content [“from.name”]; s.from_id =(string)content [“from.id”];) 我的代码运行正常。

我想我无法正确引用嵌套的JSON数据。

任何人都可以validation它,请告诉我如何在C#中引用JSON中的嵌套数据?

谢谢

我不确定你是如何解析JSON字符串的。 您是否在框架中使用类来进行反序列化?

您可以使用System.Web.Script.Serialization命名空间中定义的JavaScriptSerializer类(您可能需要添加对System.Web.dll的引用)

使用该类,您可以像这样编写代码:

 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; } } 

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

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

请参阅MSDN上的JavaScriptSerializer 。 您可能还想查看这个类似的问题 。

上述就是C#学习教程:在C#中解析JSON数据分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1002864.html

(0)
上一篇 2021年12月28日
下一篇 2021年12月28日

精彩推荐