직렬화란?
Dart 코드로 되어있는 객체를 다른 언어로 작성한 언어 및 플랫폼(예를들어 자바로 작성된 서버)에서 작동하게 하게 하기 위해 객체를 서버에 전송하거나 로컬 저장소에 저장하기 위해 적합한 형식으로 변환하는 과정.
서로다른 언어를 사용하는 플랫폼에서도 데이터를 주고받을 수 있게 하기 위해 JSON 이라는 형식을 주로 사용
JSON ( JavaScript Object Notation )
데이터를 저장하거나 전송할 때 많이 사용되는 DATA 교환 형식
JSON은 데이터를 표시하는 표현방법이며, 서버와 클라이언트 간의 데이터 교환에서 주로 사용된다.
실제로 코드 내에서 사용될 때는 Map<String, dynamic> 형태로 decode 할 수 있다.
// JSON 데이터의 일반적인 형식
// key - value
{
"name": "오상구",
"age": 7,
"isMale" : true,
"favorite_foods" : ["삼겹살", "연어", "고구마"],
"dislike_foods" : [],
"contact": {
"mobile": "010-0000-0000",
"email": null
}
}
Dart 에서 JSON 데이터 변환하기
- 직렬화 ( Dart >> JSON ) - 데이터를 보내는 용도
import 'dart:convert';
// dart 데이터
Map<String, dynamic> data = {
"name" : "Tom",
"age" : 12,
"contact" : {
"phone" : "010-000-0000",
}
};
// dart >> JSON (단일 변환)
String jsonData = jsonEncode(data);
// 여러개의 데이터 변환 (리스트 형태)
List dataList = [data1, data2];
String jsonDataList = jsonEncode(dataList);
- 역 직렬화 ( JSON >> Dart ) - 데이터를 받는 용도
import 'dart:convert';
String jsonData = """
[
{
"name" : "one",
"age" : 1,
},
{
"name" : "two"
"age" : 2,
}
]
"""
// 단일데이터인지, List형태의 복합데이터인지 모르기때문에 타입 추론 var 사용
var data = jsonDecode(jsonData);
클래스(객체) 에서 JSON 변환하기!
클래스 내에서 직렬화, 역직렬화 메서드를 구현하여 사용하면, 데이터 관리에 더 수월하다!
class User {
User({
required this.name,
required this.age,
});
String name;
int age;
// 역직렬화 - 생성자형태 (데이터를 받는용)
User.fromJson(Map<String, dynamic> map) : this(
name: map['name'],
age: map['age'],
);
// 직렬화 - 메서드형태 (데이터를 보내는용)
Map<String, dynamic> toJson() {
return {
"name" : name,
"age" : age,
}
}
}
// 사용법
User a = User.fromJson(data); // 데이터 받기
String JsonData = a.toJson(); // 데이터 보내기
## JSON 데이터 안에, 또 다른 JSON 데이터가 있는 경우!!
import 'dart:convert';
void main() {
String jsonString = """
{
"name": "오상구",
"age": 7,
"isMale" : true,
"favorite_foods" : ["삼겹살", "연어", "고구마"],
"contact": {
"mobile": "010-0000-0000",
"email": null
}
}
""";
var map = jsonDecode(jsonString);
Pet a = Pet.fromJson(map);
print(a.toJson());
}
// Pet 객체
class Pet {
String name;
int age;
bool isMale;
List<String> favorite_foods;
Contact contact;
Pet(
{required this.name,
required this.age,
required this.isMale,
required this.favorite_foods,
required this.contact});
Pet.fromJson(Map<String,dynamic> json) : this(
name: json['name'],
age: json['age'],
isMale: json['isMale'],
favorite_foods: List<String>.from(json['favorite_foods']), // List<dynamic>을 List<String>으로 변환
contact: Contact.fromJson(json["contact"]),
);
Map<String,dynamic> toJson(){
return {
"name": name,
"age" : age,
"isMale" : isMale,
"favorite_foods" : favorite_foods,
"contact" : contact,
};
}
}
// Contact 객체
class Contact {
String mobile;
String? email;
Contact({
required this.mobile,
required this.email,
});
Contact.fromJson(Map<String, dynamic> json)
: this(
mobile: json["mobile"],
email: json["email"],
);
Map<String, dynamic> toJson() {
return {
"mobile": mobile,
"email": email,
};
}
}
'Dart 문법' 카테고리의 다른 글
클래스 생성자 방식 (0) | 2024.11.18 |
---|---|
Dart 문법(6) (0) | 2024.11.04 |
Dart 문법(5) (0) | 2024.11.01 |
Dart 문법(4) (0) | 2024.10.28 |
Dart 문법(3) (0) | 2024.10.28 |