Home >Backend Development >C++ >How Can I Efficiently Create JSON Strings in C#?
Create JSON string in C#
When building an HTTP response, you often need to send data in different formats, including JSON. This question explores how to create JSON strings in C# using string builders and external libraries such as Newtonsoft.Json.
Answer:
The JSON creation process can be simplified using the Newtonsoft.Json library:
<code class="language-csharp">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);</code>
Newtonsoft.Json provides a comprehensive set of methods for serializing and deserializing various data types to and from JSON. As shown in the above example, a custom object can be easily converted into a JSON string by using its "SerializeObject" method.
In addition, please refer to the following documentation:
The above is the detailed content of How Can I Efficiently Create JSON Strings in C#?. For more information, please follow other related articles on the PHP Chinese website!