Thư viện Newtonsoft.Json (Json.NET) cung cấp enum Formatting để kiểm soát định dạng đầu ra JSON.
Các tùy chọn Formatting
| Giá trị | Mô tả |
|---|---|
Formatting.None | Không định dạng (compact), mặc định. Dùng cho truyền mạng, lưu trữ. |
Formatting.Indented | Thụt lề (pretty-print), dễ đọc. Dùng cho debug, log, config file. |
Ví dụ: Serialize với Indented
using Newtonsoft.Json;
using System;
public class Product
{
public string Name { get; set; }
public DateTime Expiry { get; set; }
public decimal Price { get; set; }
public string[] Sizes { get; set; }
}
class Program
{
static void Main()
{
var product = new Product
{
Name = "Apple",
Expiry = new DateTime(2008, 12, 28),
Price = 3.99M,
Sizes = new[] { "Small", "Medium", "Large" }
};
// Pretty print
string json = JsonConvert.SerializeObject(product, Formatting.Indented);
Console.WriteLine(json);
// Deserialize ngược lại
var deserialized = JsonConvert.DeserializeObject<Product>(json);
Console.ReadLine();
}
}
Kết quả (Indented)
{
"Name": "Apple",
"Expiry": "2008-12-28T00:00:00",
"Price": 3.99,
"Sizes": [
"Small",
"Medium",
"Large"
]
}
Ví dụ: Serialize với None (Compact)
string jsonCompact = JsonConvert.SerializeObject(product, Formatting.None);
Console.WriteLine(jsonCompact);
Kết quả (None)
{"Name":"Apple","Expiry":"2008-12-28T00:00:00","Price":3.99,"Sizes":["Small","Medium","Large"]}
Tùy chỉnh nâng cao
var settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatString = "yyyy-MM-dd", // Format ngày tùy chỉnh
NullValueHandling = NullValueHandling.Ignore, // Bỏ qua null
ContractResolver = new CamelCasePropertyNamesContractResolver() // camelCase
};
string jsonCustom = JsonConvert.SerializeObject(product, settings);
Lưu ý: .NET Core 3.0+ có sẵn System.Text.Json (namespace System.Text.Json) với hiệu suất tốt hơn, nhưng Newtonsoft.Json vẫn phổ biến và giàu tính năng hơn.