Home > Backend Development > C++ > How Can I Format JSON Output in C# for Better Readability?

How Can I Format JSON Output in C# for Better Readability?

Barbara Streisand
Release: 2025-01-22 01:46:08
Original
875 people have browsed it

How Can I Format JSON Output in C# for Better Readability?

Format JSON using C# in .NET

When serializing JSON from a configuration file, you may prefer to use a more readable format with appropriate indentation and newlines. This article solves this problem by recommending JSON.Net as an alternative to JavaScriptSerializer.

Formatting using JSON.Net

JSON.Net is a popular .NET JSON library that supports various formatting options. Here is an example of how to format JSON using JSON.Net:

<code class="language-csharp">using Newtonsoft.Json;

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, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);</code>
Copy after login

Output:

The above code produces the following formatted JSON output:

<code class="language-json">{
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ],
  "Price": 3.99,
  "Expiry": "/Date(1230447600000-0700)/",
  "Name": "Apple"
}</code>
Copy after login

JSON.Net’s Formatting.Indented option indents the JSON output, making it easier to read and understand.

For more information about JSON.Net, see the documentation on object serialization: https://www.php.cn/link/b7cda51a7b31b77fe2d5c1ee19f33496

The above is the detailed content of How Can I Format JSON Output in C# for Better Readability?. 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