Home >Backend Development >C++ >How Can I Create Formatted JSON Output in C#?

How Can I Create Formatted JSON Output in C#?

DDD
DDDOriginal
2025-01-22 01:52:09738browse

How Can I Create Formatted JSON Output in C#?

Formatted JSON Serialization in C# Applications

C#'s built-in JavaScriptSerializer often produces compact, less readable JSON. This article shows a superior method for generating formatted JSON output.

Utilizing Newtonsoft.Json (JSON.Net)

JavaScriptSerializer has limitations in its formatting capabilities. For more control and readability, Newtonsoft.Json (JSON.Net), a popular third-party library, is the recommended solution.

The following example demonstrates how JSON.Net creates properly indented JSON:

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

namespace JsonFormattingExample
{
    class Program
    {
        static void Main(string[] args)
        {
            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);
            Console.WriteLine(json);
        }
    }

    class Product
    {
        public string[] Sizes { get; set; }
        public decimal Price { get; set; }
        public DateTime Expiry { get; set; }
        public string Name { get; set; }
    }
}</code>

Output:

The resulting JSON will be neatly formatted with indentation:

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

Using JSON.Net simplifies the creation of well-formatted, human-readable JSON in your C# projects, greatly aiding in data analysis and debugging.

The above is the detailed content of How Can I Create Formatted JSON Output in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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