将 json 转换为 C# 数组? [英] Convert json to a C# array?

查看:35
本文介绍了将 json 转换为 C# 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何将包含 json 的字符串转换为 C# 数组.我有这个从 webBrowser 读取 text/json 并将其存储到一个字符串中.

Does anyone know how to convert a string which contains json into a C# array. I have this which reads the text/json from a webBrowser and stores it into a string.

string docText = webBrowser1.Document.Body.InnerText;

只需要以某种方式将该 json 字符串更改为数组.一直在看 Json.NET,但我不确定这是否是我需要的,因为我不想将数组更改为 json;但反过来.感谢您的帮助!

Just need to somehow change that json string into an array. Been looking at Json.NET but I'm not sure if that's what I need, as I don't want to change an array into json; but the other way around. Thanks for the help!

推荐答案

只需获取字符串并使用 JavaScriptSerializer 将其反序列化为本机对象.例如,有这个 json:

just take the string and use the JavaScriptSerializer to deserialize it into a native object. For example, having this json:

string json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]"; 

您需要创建一个 C# 类,例如,定义为 Person 的类:

You'd need to create a C# class called, for example, Person defined as so:

public class Person
{
 public int Age {get;set;}
 public string Name {get;set;}
}

您现在可以通过执行以下操作将 JSON 字符串反序列化为 Person 数组:

You can now deserialize the JSON string into an array of Person by doing:

JavaScriptSerializer js = new JavaScriptSerializer();
Person [] persons =  js.Deserialize<Person[]>(json);

这是一个 JavaScriptSerializer 文档的链接.

注意:我上面的代码没有经过测试,但这就是想法 测试过了.除非您正在做一些异国情调"的事情,否则使用 JavascriptSerializer 应该没问题.

Note: my code above was not tested but that's the idea Tested it. Unless you are doing something "exotic", you should be fine using the JavascriptSerializer.

这篇关于将 json 转换为 C# 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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