Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to get formatted JSON in .NET using C#?
Use Namespace Newtonsoft.Json.Formatting Newtonsoft.Json.Formatting provides formatting options to Format the Json
None − No special formatting is applied. This is the default.
Indented − Causes child objects to be indented according to the Newtonsoft.Json.JsonTextWriter.Indentation and Newtonsoft.Json.JsonTextWriter.IndentChar settings.
Example
static void Main(string[] args){
Product product = new Product{
Name = "Apple",
Expiry = new DateTime(2008, 12, 28),
Price = 3.9900M,
Sizes = new[] { "Small", "Medium", "Large" }
};
string json = JsonConvert.SerializeObject(product, Formatting.Indented);
Console.WriteLine(json);
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
Console.ReadLine();
}
class Product{
public String[] Sizes { get; set; }
public decimal Price { get; set; }
public DateTime Expiry { get; set; }
public string Name { get; set; }
}
Output
{
"Sizes": [
"Small",
"Medium",
"Large"
],
"Price": 3.9900,
"Expiry": "2008-12-28T00:00:00",
"Name": "Apple"
}
Example
static class Program{
static void Main(string[] args){
Product product = new Product{
Name = "Apple",
Expiry = new DateTime(2008, 12, 28),
Price = 3.9900M,
Sizes = new[] { "Small", "Medium", "Large" }
};
string json = JsonConvert.SerializeObject(product, Formatting.None);
Console.WriteLine(json);
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
Console.ReadLine();
}
}
class Product{
public String[] Sizes { get; set; }
public decimal Price { get; set; }
public DateTime Expiry { get; set; }
public string Name { get; set; }
}
Output
{"Sizes":["Small","Medium","Large"],"Price":3.9900,"Expiry":"2008-12-28T00:00:00","Name":"Apple"}Advertisements