如何与键/值数组转换成JSON C# [英] how to convert array with keys/values to JSON c#
问题描述
我completey新的C#和我已经给自己一个头痛的问题。我知道这可能是孩子的东西给你,但我已经花了一个小时+ googleing四周,似乎无法工作了。
I'm completey new to C# and I've already given myself a headache. I know this is probably kids stuff to you, but I've spent an hour+ googleing around and can't seem to work it out.
所有我想要做的是转换一个数组JSON。我知道PHP的好,所以这里有什么,我试图做(在PHP)的例子:
All I'm trying to do is convert an array into JSON. I know PHP well, so here's an example of what I'm trying to do (in PHP):
$myarr=array("key1"=>"value for key 1","key2"=>"value for key 2");
$jsonArray=json_encode($myarr);
所以 $ jsonArray
将是: {KEY1:KEY2关键值1:关键值2 }
现在,我试图做的正是这一点,但在C#。
Now, I'm trying to do exactly that, but in C#.
这是我迄今为止:
String[] keys = new String[] { "emailSend","toEmail"};
String[] values = new String[] {textBox2.Text,textBox1.Text};
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(keys);//final json result
MessageBox.Show(json);//show me
我使用的Visual Studio C#2010,它是(高于与code)抛出这个错误:
I'm using Visual Studio C# 2010, which is throwing this error (with the code above):
类型或命名空间名称'的JavaScriptSerializer'找不到
(是否缺少using指令或程序集引用?)
The type or namespace name 'JavaScriptSerializer' could not be found (are you missing a using directive or an assembly reference?)
这是我做错了什么在这里的任何想法?谢谢
Any ideas on what I'm doing wrong here? Thanks
推荐答案
看起来你没有一个正确的使用
语句?下面添加到文件的顶部:
Looks like you don't have a correct using
statement? Add the following to the top of your file:
使用System.Web.Script.Serialization;
修改:要得到正确格式的JSON,使用词典
而不是:
EDIT: To get correctly formatted JSON, use a Dictionary
instead:
var keyValues = new Dictionary<string, string>
{
{ "emailSend", textBox1.Text },
{ "toEmail", textBox2.Text }
};
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(keyValues);
MessageBox.Show(json);
这篇关于如何与键/值数组转换成JSON C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!