如何将c#对象转换为json对象

时间:2014-07-13 12:38:37

标签: c# asp.net json

我写这段代码:

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

该代码正确地将imgUrl转换为json对象并且响应结果为:

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

我如何添加" url"字段到我的json对象?

例如我想转换为:

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

1 个答案:

答案 0 :(得分:3)

您可以将imgUrls映射到匿名对象而不是字符串数组:

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

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