Create JSON string in C#
XML is often used for structured representation when sending data in HTTP responses. However, JSON (JavaScript Object Notation) is growing in popularity because it is lightweight and easy to parse. Here's how to generate JSON strings in C# using the powerful Newtonsoft.Json library:
First, install the Newtonsoft.Json NuGet package.
Consider the following code:
<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>
Here, we define a Product class and fill it with properties. The JsonConvert.SerializeObject method converts an object into a JSON string that can be assigned to a json variable.
Documentation for JSON serialization and deserialization can be found here:
JSON serialization and deserialization
The above is the detailed content of How to Generate JSON Strings in C# using Newtonsoft.Json?. For more information, please follow other related articles on the PHP Chinese website!