我只是使用XmlWriter创建了一些XML,以便在HTTP响应中发回。如何创建JSON字符串?我猜你会使用stringbuilder来构建JSON字符串,然后将响应格式化为JSON?
当前回答
看看http://www.codeplex.com/json/上的json-net。aspx项目。为什么要重新发明轮子?
其他回答
这个库非常适合用于c#中的JSON
http://james.newtonking.com/pages/json-net.aspx
编码使用
JSON数组的简单对象EncodeJsObjectArray()
public class dummyObject
{
public string fake { get; set; }
public int id { get; set; }
public dummyObject()
{
fake = "dummy";
id = 5;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('[');
sb.Append(id);
sb.Append(',');
sb.Append(JSONEncoders.EncodeJsString(fake));
sb.Append(']');
return sb.ToString();
}
}
dummyObject[] dummys = new dummyObject[2];
dummys[0] = new dummyObject();
dummys[1] = new dummyObject();
dummys[0].fake = "mike";
dummys[0].id = 29;
string result = JSONEncoders.EncodeJsObjectArray(dummys);
论点: [29,“迈克”[5],“笨蛋”]
漂亮的用法
Pretty print JSON数组PrettyPrintJson()字符串扩展方法
string input = "[14,4,[14,\"data\"],[[5,\"10.186.122.15\"],[6,\"10.186.122.16\"]]]";
string result = input.PrettyPrintJson();
结果是:
[
14,
4,
[
14,
"data"
],
[
[
5,
"10.186.122.15"
],
[
6,
"10.186.122.16"
]
]
]
如果您试图创建一个web服务,通过JSON向web页面提供数据,请考虑使用ASP。. NET Ajax工具包:
http://www.asp.net/learn/ajax/tutorial-05-cs.aspx
它会自动将你通过webservice服务的对象转换为json,并创建你可以用来连接到它的代理类。
如果你想避免创建一个类和创建JSON,那么创建一个动态对象和序列化对象。
dynamic data = new ExpandoObject();
data.name = "kushal";
data.isActive = true;
// convert to JSON
string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
读取JSON并像这样反序列化:
// convert back to Object
dynamic output = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
// read a particular value:
output.name.Value
ExpandoObject来自System。动态名称空间。
使用Newtonsoft。Json让它变得更简单:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
文档:序列化和反序列化JSON
推荐文章
- 新建T()
- Ajax会调用什么样的响应,比如'for (;;);{json data}的意思?
- 如何将枚举绑定到WPF中的组合框控件?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 拒绝访问该路径
- Visual Studio - Resx文件默认“内部”为“公共”
- 使用linq转换列表到字典,不用担心重复
- 单元测试:日期时间。现在
- 什么是回调?
- 返回匿名类型的结果?
- 何时使用IList,何时使用List
- ConfigurationManager。AppSettings在.NET Core 2.0中可用?
- 在c#的控制台应用程序中使用'async
- 使用Jackson将JSON字符串转换为漂亮的打印JSON输出
- 在单元测试中设置HttpContext.Current.Session