简体   繁体   中英

how to convert array with keys/values to JSON c#

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.

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

so $jsonArray will be: {"key1":"value for key 1","key2":"value for key 2"}

Now, I'm trying to do exactly that, but in 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):

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:

using System.Web.Script.Serialization;

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

how about using JSON.NET and the JObject class?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM