一尘不染

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

c#

我只是使用XmlWriter创建一些XML以通过HTTP响应发送回。您将如何创建JSON字符串。我假设您只是使用stringbuilder来构建JSON字符串,并且它们将响应格式设置为JSON?


阅读 793

收藏
2020-05-19

共1个答案

一尘不染

您可以使用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();
2020-05-19