เยี่ยมเลยครับ 😎
วันนี้เรามาเรียนรู้ตัวสำคัญอีกตัวหนึ่งของ ASP.NET Core คือ
🧩 Microsoft.AspNetCore.Mvc.NewtonsoftJson
🔍 คืออะไร?
Microsoft.AspNetCore.Mvc.NewtonsoftJson
คือ แพ็กเกจ (NuGet Package) ที่ใช้เพื่อให้ ASP.NET Core MVC หรือ Web API
สามารถใช้ Newtonsoft.Json (Json.NET) สำหรับการ Serialize / Deserialize JSON ได้
📘 1️⃣ ทำไมถึงต้องใช้ Newtonsoft.Json?
ตั้งแต่ .NET Core 3.0 เป็นต้นมา
Microsoft เปลี่ยนมาใช้ System.Text.Json เป็นตัว Serialize JSON เริ่มต้น
แต่ Newtonsoft.Json ยังมีฟีเจอร์ที่ System.Text.Json ยังทำไม่ได้ทั้งหมด เช่น:
ฟีเจอร์ | Newtonsoft.Json | System.Text.Json |
---|---|---|
รองรับ [JsonProperty] |
✅ | ⚠️ Partial |
รองรับการ Serialize/Deserialize ซับซ้อน | ✅ | ❌ |
รองรับ ReferenceLoopHandling |
✅ | ❌ |
รองรับ JsonConverter ขั้นสูง |
✅ | ⚠️ บางส่วน |
รองรับ Dynamic JSON (JObject , JArray ) |
✅ | ❌ |
ดังนั้นถ้าโปรเจกต์ของคุณต้อง:
-
ใช้ Library เก่า
-
ใช้
JObject
,JToken
,JsonProperty
,JsonIgnore
-
หรือมี Model ที่ซับซ้อน
👉 ควรใช้ Microsoft.AspNetCore.Mvc.NewtonsoftJson
⚙️ 2️⃣ ติดตั้ง NuGet
dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson
🧱 3️⃣ การตั้งค่าใน Program.cs
(หรือ Startup.cs
สำหรับ .NET Core เก่า)
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddControllers()
.AddNewtonsoftJson(options =>
{
// ✅ ป้องกันการ Loop ของ Reference
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
// ✅ ให้ JSON แสดงชื่อ property ตามรูปแบบ Camel Case
options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
// ✅ กำหนดการจัดรูปแบบให้อ่านง่าย (Pretty Print)
options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
});
var app = builder.Build();
app.MapControllers();
app.Run();
🧩 4️⃣ ตัวอย่าง Model
public class User
{
[JsonProperty("user_id")]
public int Id { get; set; }
[JsonProperty("user_name")]
public string Name { get; set; }
[JsonIgnore] // ❌ จะไม่ถูก Serialize
public string Password { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string City { get; set; }
public string Country { get; set; }
}
ใช้
[JsonProperty]
,[JsonIgnore]
ได้เต็มรูปแบบ (Newtonsoft เท่านั้น)
🚀 5️⃣ ตัวอย่าง Controller
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
[HttpGet]
public IActionResult GetUser()
{
var user = new User
{
Id = 1,
Name = "Jen Mai",
Password = "secret",
Address = new Address { City = "Bangkok", Country = "Thailand" }
};
// Newtonsoft จะ Serialize ให้อัตโนมัติ
return Ok(user);
}
[HttpPost]
public IActionResult CreateUser([FromBody] User user)
{
// Newtonsoft จะ Deserialize JSON เป็น Object ให้อัตโนมัติ
return Ok($"สร้างผู้ใช้ชื่อ {user.Name} เรียบร้อย");
}
}
เมื่อเรียก /api/users
จะได้ JSON ดังนี้ 👇
{
"user_id": 1,
"user_name": "Jen Mai",
"address": {
"city": "Bangkok",
"country": "Thailand"
}
}
🧠 6️⃣ การใช้ JObject
/ JArray
Newtonsoft.Json มีคลาส Dynamic JSON ที่ชื่อ JObject
และ JArray
ใช้ได้ดีเวลาไม่รู้รูปแบบของ JSON ล่วงหน้า
[HttpPost("dynamic")]
public IActionResult ReadJson([FromBody] JObject data)
{
string name = data["user_name"]?.ToString();
return Ok($"Hello {name}!");
}
หรือแบบ Array:
[HttpPost("array")]
public IActionResult ReadJsonArray([FromBody] JArray array)
{
var count = array.Count;
return Ok($"มีทั้งหมด {count} รายการ");
}
🧩 7️⃣ การใช้ Newtonsoft ในส่วนอื่นของโปรเจกต์
คุณยังสามารถใช้ Newtonsoft โดยตรงในโค้ดปกติ เช่น
using Newtonsoft.Json;
// Serialize
var json = JsonConvert.SerializeObject(user, Formatting.Indented);
// Deserialize
var newUser = JsonConvert.DeserializeObject<User>(json);
🧮 8️⃣ การเปรียบเทียบ System.Text.Json vs Newtonsoft.Json
หัวข้อ | System.Text.Json | Newtonsoft.Json |
---|---|---|
Performance (เร็ว) | ✅ | ⚠️ ช้ากว่าเล็กน้อย |
ใช้งานกับ Library เก่า | ❌ | ✅ |
ความยืดหยุ่น (custom converter) | ⚠️ จำกัด | ✅ ดีมาก |
รองรับ Reference Loop | ❌ | ✅ |
รองรับ Attribute ของ JSON เก่า (JsonProperty ) |
❌ | ✅ |
✅ 9️⃣ สรุป
หัวข้อ | รายละเอียด |
---|---|
Package | Microsoft.AspNetCore.Mvc.NewtonsoftJson |
ใช้ทำอะไร | ใช้ Newtonsoft.Json แทน System.Text.Json |
ติดตั้งผ่าน | dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson |
เหมาะกับ | API ที่มี Model ซับซ้อน, ใช้ JObject , ต้องการ custom serialization |
จุดเด่น | มี Feature ครบ, ยืดหยุ่น, ควบคุมรูปแบบ JSON ได้ดี |
อยากไหมครับให้ผมสร้าง โปรเจกต์ Web API ตัวอย่างเต็ม (พร้อม Swagger)
โดยใช้ Microsoft.AspNetCore.Mvc.NewtonsoftJson
+ ตัวอย่าง Serialize/Deserialize จริงแบบครบทุกแบบ
(เหมาะสำหรับเรียนรู้และนำไปใช้กับโปรเจกต์ของคุณได้เลย) ?