ใช้ Library Newtonsoft.Json (Json.NET) ซึ่งเป็น Standard สำหรับ JSON Serialization ใน .NET
Namespace: Newtonsoft.Json
Enum สำคัญ: Formatting มี 2 ค่า:
Formatting.None: ไม่จัดรูปแบบ (Compact) - DefaultFormatting.Indented: จัดรูปแบบมี Indentation (อ่านง่าย)
ตัวอย่าง: Serialize ด้วย 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; }
}
static void Main()
{
var product = new Product
{
Name = "Apple",
Expiry = new DateTime(2008, 12, 28),
Price = 3.99M,
Sizes = new[] { "Small", "Medium", "Large" }
};
// Serialize ด้วย Indented
string json = JsonConvert.SerializeObject(product, Formatting.Indented);
Console.WriteLine(json);
// Deserialize กลับ
var deserialized = JsonConvert.DeserializeObject<Product>(json);
Console.ReadLine();
}
ผลลัพธ์ (Indented)
{
"Name": "Apple",
"Expiry": "2008-12-28T00:00:00",
"Price": 3.99,
"Sizes": [
"Small",
"Medium",
"Large"
]
}
ตัวอย่าง: Serialize ด้วย None (Compact)
string json = JsonConvert.SerializeObject(product, Formatting.None);
Console.WriteLine(json);
ผลลัพธ์ (None)
{"Name":"Apple","Expiry":"2008-12-28T00:00:00","Price":3.99,"Sizes":["Small","Medium","Large"]}
ตัวเลือกเพิ่มเติม (JsonSerializerSettings)
var settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore, // ไม่ serialize null
DateFormatString = "yyyy-MM-dd", // รูปแบบวันที่
ContractResolver = new CamelCasePropertyNamesContractResolver() // camelCase
};
string json = JsonConvert.SerializeObject(product, settings);
หมายเหตุ
- ใน .NET Core 3.0+ มี
System.Text.JsonBuilt-in ใช้JsonSerializerOptions { WriteIndented = true } - Newtonsoft.Json ยังคงมีฟีเจอร์มากกว่า และรองรับ .NET Framework แบบเก่า