[英]how to convert array with keys/values to JSON c#
I'm completey new to C# and I've already given myself a headache. 我是C#的新手,我已经让自己头疼了。 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.
我知道这可能是孩子们给你的东西,但我花了一个小时+谷歌周围,似乎无法解决它。
All I'm trying to do is convert an array into JSON. 我要做的就是将数组转换为JSON。 I know PHP well, so here's an example of what I'm trying to do (in PHP):
我很了解PHP,所以这里是我正在尝试做的一个例子(在PHP中):
$myarr=array("key1"=>"value for key 1","key2"=>"value for key 2");
$jsonArray=json_encode($myarr);
so $jsonArray
will be: {"key1":"value for key 1","key2":"value for key 2"}
所以
$jsonArray
将是: {"key1":"value for key 1","key2":"value for key 2"}
Now, I'm trying to do exactly that, but in C#. 现在,我正在努力做到这一点,但在C#中。
This is what I have so far: 这是我到目前为止:
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
I'm using Visual Studio C# 2010, which is throwing this error (with the code above): 我正在使用Visual Studio C#2010,它会抛出此错误(使用上面的代码):
The type or namespace name 'JavaScriptSerializer' could not be found (are you missing a using directive or an assembly reference?)
找不到类型或命名空间名称'JavaScriptSerializer'(您是否缺少using指令或程序集引用?)
Any ideas on what I'm doing wrong here? 关于我在这里做错了什么的想法? Thanks
谢谢
Looks like you don't have a correct using
statement? 看起来你没有正确的
using
声明? Add the following to the top of your file: 将以下内容添加到文件顶部:
using System.Web.Script.Serialization;
EDIT : To get correctly formatted JSON, use a Dictionary
instead: 编辑 :要获得格式正确的JSON,请使用
Dictionary
:
var keyValues = new Dictionary<string, string>
{
{ "emailSend", textBox1.Text },
{ "toEmail", textBox2.Text }
};
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(keyValues);
MessageBox.Show(json);
how about using JSON.NET and the JObject class? 如何使用JSON.NET和JObject类?
var obj = new JObject();
obj["One"] = "Value One";
obj["Two"] = "Value Two";
obj["Three"] = "Value Three";
var serialized = JsonConvert.SerializeObject(obj);
gives you 给你
{"One":"Value One","Two":"Value Two","Three":"Value Three"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.