Home >Backend Development >C++ >How to Pretty-Print JSON in .NET Core Using C#?

How to Pretty-Print JSON in .NET Core Using C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-22 01:36:09230browse

How to Pretty-Print JSON in .NET Core Using C#?

.NET Core C# JSON Formatting Guide

When working with JSON data in a .NET environment, it is useful to format JSON to enhance readability. .NET's default JSON parser, JavaScriptSerializer, does not provide convenient formatting methods.

Use JSON.Net

It is recommended to use the JSON.Net library to format JSON data in .NET. Here is an example of how to format using JSON.Net:

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

namespace JsonPrettyPrint
{
    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>

JSON.Net uses the Formatting.Indented option to format the output JSON.

Output results

The formatted JSON output looks like this:

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

More information

For more information about JSON.Net, please refer to the official documentation: Object serialization

The above is the detailed content of How to Pretty-Print JSON in .NET Core Using 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