我只是使用XmlWriter创建一些XML以通过HTTP响应发送回。您将如何创建JSON字符串。我假设您只是使用stringbuilder来构建JSON字符串,并且它们将响应格式设置为JSON?
您可以使用JavaScriptSerializer类,查看本文以构建有用的扩展方法。
文章中的代码:
namespace ExtensionMethods { public static class JSONHelper { public static string ToJSON(this object obj) { JavaScriptSerializer serializer = new JavaScriptSerializer(); return serializer.Serialize(obj); } public static string ToJSON(this object obj, int recursionDepth) { JavaScriptSerializer serializer = new JavaScriptSerializer(); serializer.RecursionLimit = recursionDepth; return serializer.Serialize(obj); } } }
用法:
using ExtensionMethods; ... List<Person> people = new List<Person>{ new Person{ID = 1, FirstName = "Scott", LastName = "Gurthie"}, new Person{ID = 2, FirstName = "Bill", LastName = "Gates"} }; string jsonString = people.ToJSON();