Home > Backend Development > C++ > How to Generate JSON Strings in C# using Newtonsoft.Json?

How to Generate JSON Strings in C# using Newtonsoft.Json?

Barbara Streisand
Release: 2025-01-22 00:14:10
Original
657 people have browsed it

How to Generate JSON Strings in C# using Newtonsoft.Json?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template