TIL
[TIL] Dart에서 Json 데이터 사용하기
chengzior
2024. 11. 28. 21:07
통신할 때 보통 Json 형태의 String 데이터를 주고 받는다
{
"name": "오상구",
"age": 7
}
dart에서 사용해주기 위해 역직렬화를 해줘야 한다. (발음도 어려움ㅡㅡ;)
역직렬화: json 형태의 문자열을 객체로 변환하는 것
String -> Map -> 객체
* String -> Map [jsondecode 함수]
* Map -> 객체 [객체에 fromJson 네임드 생성자를 구현해서 사용]
순서
1. jsonDecode 이용해서 Map 형태로 변환
2. 객체에 fromJson 네임드 생성자를 구현해서 사용
void main() {
//이런 형태의 json 데이터를 dart에서 사용하고자 함.
String petData = """
{
"name": "오상구",
"age": 7,
"isMale" : true,
"favorite_foods" : ["삼겹살", "연어", "고구마"],
"contact": {
"mobile": "010-0000-0000",
"email": null
}
}
""";
//1번. map 형태로 변환
Map<String, dynamic> map = jsonDecode(petData);
Pet pet = Pet.fromJson(map);
print(pet.toJson());
}
//2번. 객체 생성
class Pet {
String name;
int age;
bool isMale;
List<String> favoriteFoods;
Contact contact;
Pet({
required this.name,
required this.age,
required this.isMale,
required this.favoriteFoods,
required this.contact,
});
Pet.fromJson(Map<String, dynamic> json)
: this(
name: json['name'],
age: json['age'],
isMale: json['isMale'],
favoriteFoods: List<String>.from(json['favorite_foods']),
contact: Contact.fromJson(json['contact']),
);
Map<String,dynamic> toJson(){
return {
"name": name,
"age":age,
"isMale":isMale,
"favorite_foods":favoriteFoods,
"contact": contact.toJson(),
};
}
}
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,
};
}
}
조금 헷갈리긴 하는데,
반복해서 치다보면 익숙해질듯...!