JSON (JavaScript Object Notation) เป็นรูปแบบข้อมูลมาตรฐานที่ใช้สำหรับการแลกเปลี่ยนข้อมูลระหว่าง Client (เช่น Web/Mobile App) และ Server ข้อมูล JSON เป็นเพียง Text String ที่มีโครงสร้างแบบ Object หรือ Array
ใน TypeScript การจัดการ JSON ทำได้ง่าย เนื่องจากมีฟังก์ชัน Global ที่รองรับการทำงานนี้โดยตรง
1. การแปลงข้อมูลพื้นฐาน (Parsing & Stringifying)
TypeScript/JavaScript ใช้ Global Object ที่ชื่อว่า JSON ในการแปลงข้อมูล
A. JSON Decoding: แปลง String เป็น Object
ใช้ฟังก์ชัน JSON.parse() เพื่อแปลง JSON String ที่ได้รับมาให้เป็น Object ที่สามารถเรียกใช้งานได้
// 1. JSON String Data ที่ได้รับจาก Server
const jsonString: string = `
[
{ "score": 40, "overtime": false },
{ "score": 80, "overtime": true }
]
`;
// 2. แปลง JSON String ให้เป็น Object (Array of Objects)
const scores = JSON.parse(jsonString);
// scores จะถูกอนุมานชนิดเป็น Array of any (any[])
console.log(scores.length); // 2
console.log(`First score is ${scores[0].score}`); // First score is 40
B. JSON Encoding: แปลง Object เป็น String
ใช้ฟังก์ชัน JSON.stringify() เพื่อแปลง TypeScript Object ให้เป็น JSON String สำหรับส่งไปยัง Server
// Object หรือ Array ที่ต้องการแปลง
const scores = [
{ score: 40 },
{ score: 80, overtime: true, specialGuest: null } // รองรับ null, boolean
];
// แปลง Object ให้เป็น JSON String
const jsonText: string = JSON.stringify(scores);
console.log(typeof jsonText); // string
// Output: [{"score":40},{"score":80,"overtime":true,"specialGuest":null}]
2. การสร้าง Model เพื่อความปลอดภัยของชนิดข้อมูล (Type Safety)
ความท้าทายหลักใน TypeScript คือการทำให้ข้อมูล JSON ที่ถูก JSON.parse() กลายเป็น Object ที่มีชนิดข้อมูลที่ชัดเจน (Strongly-Typed) เราใช้ Interface หรือ Class ในการกำหนดโครงสร้าง (Model)
A. การกำหนด Model ด้วย Interface
Interface เป็นวิธีที่ง่ายที่สุดในการกำหนดโครงสร้างข้อมูล JSON:
// Interface สำหรับโครงสร้างข้อมูล
interface Address {
street: string;
city: string;
}
interface User {
firstName: string;
address: Address; // ใช้ Interface ที่ซ้อนกัน
}
เมื่อได้รับ JSON String มาแล้ว เราสามารถประกาศตัวแปรให้เป็นชนิด User ได้ แต่ต้องแน่ใจว่าโครงสร้างตรงกัน:
const jsonString = '{"firstName":"Ebiwayo","address":{"street":"My Str.","city":"New York"}}';
// ประกาศตัวแปรเป็นชนิด User หลังจาก parse
const user: User = JSON.parse(jsonString);
console.log(user.address.city); // New York
B. การแปลงเป็น Class Object ด้วย Factory Method
สำหรับการทำงานที่ซับซ้อนขึ้น (เช่น ต้องมี Methods ภายใน Object) เราจะใช้ Class และสร้าง Static Factory Method ที่ชื่อว่า fromJson เพื่อแปลงข้อมูล Map (หรือ Object) ที่ได้จากการ parse ให้เป็น Instance ของ Class
class User {
constructor(
public firstName: string,
public address: Address // ใช้ Interface เป็นชนิดข้อมูล
) {}
// Static Factory Method: ใช้รับ Object ที่ถูกแปลงมาแล้ว (JSON Object)
static fromJson(json: { [key: string]: any }): User {
// ตรวจสอบและแปลงข้อมูล Address ที่ซ้อนกัน
const addressData = json['address'];
const address = new Address(addressData.street, addressData.city);
return new User(json['firstName'], address);
}
// Method สำหรับแปลงกลับไปเป็น JSON-ready Object (ถ้าต้องการ)
public toJson(): any {
return {
firstName: this.firstName,
address: this.address
};
}
}
3. การจัดการ JSON Array (List of Objects)
เมื่อข้อมูล JSON มาในรูปแบบ Array (หลายรายการ) เราต้องใช้ฟังก์ชัน .map() ของ Array ในการวนซ้ำเพื่อแปลง Object ทีละตัวให้เป็น Instance ของ Model Class
const jsonArray = `[
{ "firstName": "Alice", "address": {...} },
{ "firstName": "Bob", "address": {...} }
]`;
// 1. แปลง JSON String เป็น Array of generic objects
const jsonObjects: any[] = JSON.parse(jsonArray);
// 2. ใช้ .map() เพื่อแปลง Array of any เป็น Array of User (User[])
const userList: User[] = jsonObjects.map(obj => User.fromJson(obj));
console.log(userList[0].firstName); // Alice
console.log(userList.length); // 2
ข้อแตกต่างจาก Dart: TypeScript ไม่มีระบบ Code Generation อย่าง
json_serializableที่ทำงานในขั้นตอน Build Time โดยตรง สำหรับงานซับซ้อน นักพัฒนา TS อาจใช้ไลบรารี Runtime เช่นclass-transformerเพื่อทำหน้าที่แปลงข้อมูล Object อัตโนมัติ แต่โดยทั่วไปการใช้ Interfaces และ Static Factory Methods ถือเป็นวิธีมาตรฐานและเพียงพอต่อการทำ Type Safety ในโค้ดพื้นฐาน