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>
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>
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!