简体   繁体   中英

How to convert c# object to json object

I write this code:

var filesNames = Directory.GetFiles(Server.MapPath("~/Image"))
                          .Select(x => Path.GetFileName(x));
var imgUrls = filesNames.Select(x => ResolveUrl(String.Format("~/Image/{0}",  x))).ToArray();

string[][] newKeys = imgUrls.Select(x => new string[] { x }).ToArray();
JavaScriptSerializer jss = new JavaScriptSerializer();

string json = jss.Serialize(newKeys);
Response.Write(json);

that code correctly convert imgUrl to json object and response result is:

[["/Image/t1.jpg"],["/Image/t2.jpg"],["/Image/t3.jpg"],["/Image/t4.jpg"]]

How can i add "url" fields to my json object?

for example i want convert to this:

[["url:","/Image/t1.jpg"],["url:","/Image/t2.jpg"],["url:","/Image/t3.jpg"],["url:","/Image/t4.jpg"]]

You could map the imgUrls into anonymous objects instead of string arrays:

var newKeys = imgUrls.Select(x => new { url = x }).ToArray();

JavaScriptSerializer jss = new JavaScriptSerializer();
string json = jss.Serialize(newKeys);
Response.Write(json);

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