c# - 如何在C#中创建JSON字符串

我刚刚使用XMLWriter创建了一些XML,以便在HTTP响应中发送回来。如何创建JSON字符串。我假设您只需要使用一个StringBuilder来构建JSON字符串,然后将您的响应格式化为JSON?


最佳答案:

您可以使用JavaScriptSerializer class,选中this article来构建一个有用的扩展方法。
文章代码:

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

评论