Create JSON string in C#
XML is a commonly used format when returning HTTP response data. However, JSON (JavaScript Object Notation) is becoming increasingly popular due to its simplicity and wide support. This article explores how to create a JSON string in C# using the string builder and format the response as JSON.
Newtonsoft.Json library
To simplify the process, it is highly recommended to use the Newtonsoft.Json library. You can easily convert an object to a JSON string by using the JsonConvert.SerializeObject() method. Here's an example:
<code class="language-csharp">// 定义一个Product对象 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" }; // 将Product对象转换为JSON字符串 string json = JsonConvert.SerializeObject(product);</code>
The generated json string will represent the Product object in JSON format.
Documentation
For complete documentation on serializing and deserializing JSON using Newtonsoft.Json, please see the following resources:
The above is the detailed content of How to Efficiently Create JSON Strings in C#?. For more information, please follow other related articles on the PHP Chinese website!