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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1056121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 07:08:54  来源:igfitidea点击:

How to create JSON string in C#

c#asp.netjson

提问by PositiveGuy

I just used the XmlWriter to create some XML to send back in an HTTP response. How would you create a JSON string. I assume you would just use a stringbuilder to build the JSON string and them format your response as JSON?

我只是使用 XmlWriter 创建一些 XML 以在 HTTP 响应中发回。您将如何创建 JSON 字符串。我假设您只会使用 stringbuilder 来构建 JSON 字符串,然后它们将您的响应格式化为 JSON?

采纳答案by CMS

You could use the JavaScriptSerializer class, check this articleto build an useful extension method.

您可以使用JavaScriptSerializer 类,查看本文以构建有用的扩展方法。

Code from 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);
        }
    }
}

Usage:

用法:

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

回答by Eduardo Scoz

If you're trying to create a web service to serve data over JSON to a web page, consider using the ASP.NET Ajax toolkit:

如果您尝试创建 Web 服务以通过 JSON 向网页提供数据,请考虑使用 ASP.NET Ajax 工具包:

http://www.asp.net/learn/ajax/tutorial-05-cs.aspx

http://www.asp.net/learn/ajax/tutorial-05-cs.aspx

It will automatically convert your objects served over a webservice to json, and create the proxy class that you can use to connect to it.

它会自动将通过 Web 服务提供的对象转换为 json,并创建可用于连接到它的代理类。

回答by Hugoware

This library is very good for JSON from C#

这个库非常适合 C# 中的 JSON

http://james.newtonking.com/pages/json-net.aspx

http://james.newtonking.com/pages/json-net.aspx

回答by Josh

Take a look at http://www.codeplex.com/json/for the json-net.aspx project. Why re-invent the wheel?

查看http://www.codeplex.com/json/的 json-net.aspx 项目。为什么要重新发明轮子?

回答by Tamas Czinege

If you can't or don't want to use the two built-in JSON serializers (JavaScriptSerializerand DataContractJsonSerializer) you can try the JsonExSerializerlibrary - I use it in a number of projects and works quite well.

如果您不能或不想使用两个内置的 JSON 序列化程序(JavaScriptSerializerDataContractJsonSerializer),您可以尝试JsonExSerializer库 - 我在许多项目中使用它并且效果很好。

回答by Steve

The DataContractJSONSerializerwill do everything for you with the same easy as the XMLSerializer. Its trivial to use this in a web app. If you are using WCF, you can specify its use with an attribute. The DataContractSerializer family is also very fast.

DataContractJSONSerializer会为你做的一切与容易,因为XmlSerializer的相同。在网络应用程序中使用它很简单。如果您使用 WCF,则可以使用属性指定其用途。DataContractSerializer 系列也非常快。

回答by Joe Chung

This code snippet uses the DataContractJsonSerializer from System.Runtime.Serialization.Json in .NET 3.5.

此代码段使用 .NET 3.5 中 System.Runtime.Serialization.Json 中的 DataContractJsonSerializer。

public static string ToJson<T>(/* this */ T value, Encoding encoding)
{
    var serializer = new DataContractJsonSerializer(typeof(T));

    using (var stream = new MemoryStream())
    {
        using (var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, encoding))
        {
            serializer.WriteObject(writer, value);
        }

        return encoding.GetString(stream.ToArray());
    }
}

回答by mythz

You can also try my ServiceStack JsonSerializerit's the fastest .NET JSON serializerat the moment. It supports serializing DataContracts, any POCO Type, Interfaces, Late-bound objects including anonymous types, etc.

你也可以试试我的 ServiceStack JsonSerializer,它是目前最快的 .NET JSON 序列化器。它支持序列化 DataContracts、任何 POCO 类型、接口、包括匿名类型在内的后期绑定对象等。

Basic Example

基本示例

var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = JsonSerializer.SerializeToString(customer);
var fromJson = JsonSerializer.DeserializeFromString<Customer>(json); 

Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100xslower than the other JSON serializers.

注意:只有在性能对您不重要的情况下才使用 Microsoft 的 JavaScriptSerializer,因为我不得不将它排除在我的基准测试之外,因为它比其他 JSON 序列化程序慢40 到 100 倍

回答by Orr

Using Newtonsoft.Jsonmakes it really easier:

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

Documentation: Serializing and Deserializing JSON

文档:序列化和反序列化 JSON

回答by Subtle Fox

If you need complex result (embedded) create your own structure:

如果您需要复杂的结果(嵌入式),请创建您自己的结构:

class templateRequest
{
    public String[] registration_ids;
    public Data data;
    public class Data
    {
        public String message;
        public String tickerText;
        public String contentTitle;
        public Data(String message, String tickerText, string contentTitle)
        {
            this.message = message;
            this.tickerText = tickerText;
            this.contentTitle = contentTitle;
        }                
    };
}

and then you can obtain JSON string with calling

然后您可以通过调用获取JSON字符串

List<String> ids = new List<string>() { "id1", "id2" };
templateRequest request = new templeteRequest();
request.registration_ids = ids.ToArray();
request.data = new templateRequest.Data("Your message", "Your ticker", "Your content");

string json = new JavaScriptSerializer().Serialize(request);

The result will be like this:

结果将是这样的:

json = "{\"registration_ids\":[\"id1\",\"id2\"],\"data\":{\"message\":\"Your message\",\"tickerText\":\"Your ticket\",\"contentTitle\":\"Your content\"}}"

Hope it helps!

希望能帮助到你!