Serialize JSON into an easy-to-read format using C# and JSON.Net
When processing JSON in a .NET environment using C#, you may need to serialize the JSON into formatted text that is easy to read. By default, the JSON generated by JavaScriptSerializer is very compact and difficult to read. To solve this problem, you can use the popular JSON library JSON.Net, which provides more advanced features.
Install JSON.Net
First, install the JSON.Net package via NuGet or the package manager console:
<code>Install-Package Newtonsoft.Json</code>
Format JSON using JSON.Net
To format JSON using JSON.Net, just modify the SerializeObject method as follows:
<code>using Newtonsoft.Json; ... string json = JsonConvert.SerializeObject(object, Formatting.Indented);</code>
Formatting.Indented
parameter ensures that the generated JSON is formatted with indentation and newlines, improving readability.
Example
Consider the following example:
<code>Product product = new Product { Name = "Apple", Expiry = new DateTime(2008, 12, 28), Price = 3.99M, Sizes = new[] { "Small", "Medium", "Large" } }; string json = JsonConvert.SerializeObject(product, Formatting.Indented);</code>
This code will generate the following formatted JSON:
<code>{ "Sizes": [ "Small", "Medium", "Large" ], "Price": 3.99, "Expiry": "/Date(1230447600000-0700)/", "Name": "Apple" }</code>
Summary
By leveraging the power of JSON.Net, you can easily format JSON in your C# application to make it easier to read and understand, making debugging and analysis easier.
The above is the detailed content of How to Make JSON Human-Readable in C# Using JSON.Net?. For more information, please follow other related articles on the PHP Chinese website!