본문 바로가기

flutter앱개발과정

Json 직렬화 역직렬화

✅ 직렬화 (Serialization)

객체 → Map → JSON 문자열

  1. 객체를 Map으로 변환 → toJson() 메서드 필요
  2. Map을 JSON 문자열로 변환 → jsonEncode() 사용
import 'dart:convert';

class Person {
  String name;
  int age;

  Person(this.name, this.age);

  // toJson: 객체를 Map으로 변환
  Map<String, dynamic> toJson() => {
    'name': name,
    'age': age,
  };
}

void main() {
  Person person = Person('홍길동', 30);
  String jsonString = jsonEncode(person.toJson());
  print(jsonString);  // {"name":"홍길동","age":30}
}

✅ 역직렬화 (Deserialization)

JSON 문자열 → Map → 객체

  1. 문자열을 Map으로 변환 → jsonDecode() 사용
  2. Map을 객체로 변환 → fromJson() 생성자 필요
import 'dart:convert';

class Person {
  String name;
  int age;

  Person(this.name, this.age);

  // fromJson: Map을 객체로 변환
  Person.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        age = json['age'];
}

void main() {
  String jsonString = '{"name":"홍길동","age":30}';
  Map<String, dynamic> userMap = jsonDecode(jsonString);
  Person person = Person.fromJson(userMap);
  print('${person.name}, ${person.age}');  // 홍길동, 30
}

 

👩🏻‍💻실습

import 'dart:convert';

//직렬화 : 객체를 JSON 형태의 문자열로 변환할 때
//       객체 -> Map -> String
//       jsonEncode
//       객체에 toJson메서드 구현
//역직렬화 : JSON형태의 문자열을 객체로 변환할 때
//         String -> Map -> 객체로 바궈준다
//         String -> Map : jsonDecode 함수
//         Map -> 객체 : 객체에 fromJson named 생성자를 구현해서 사용!

void main() {
  //Human
  String easyJson = """
{
  "name" : "오상구",
  "age" : 7,
  "isMale" : true
}
""";
//1. String -> Map 형태로 바꾼다.
  Map<String, dynamic> easyMap = jsonDecode(easyJson);
//3. Map -> class 객체로 바꾼다.
  Human human = Human.fromJson(easyMap);
  print(human.toJson());

//HumanDetail
  String hardJson = """
{
  "name": "오상구",
	"age": 7,
	"isMale" : true,
	"favorite_foods" : ["삼겹살", "연어", "고구마"],
	"contact": {
		"mobile": "010-0000-0000",
		"email": null
	}
}
""";

//1.jsonString -> Map 형태로 바꾼다
  Map<String, dynamic> hardMap = jsonDecode(hardJson);

//3. class를 정의했으니 객체로 만든다.(Map을)
  HumanDetail humanDetail = HumanDetail.fromJson(hardMap);

  print(humanDetail.toJson());
}

//2. class를 정의한다.
class Human {
  String name;
  int age;
  bool isMale;

  Human({required this.name, required this.age, required this.isMale});

// fromJson named 생성자 만들기
  Human.fromJson(Map<String, dynamic> map)
      : this(name: map['name'], age: map['age'], isMale: map['isMale']);

//Map<String,dynamic> return해주는 toJson만들기
  Map<String, dynamic> toJson() {
    return {'name': name, 'age': age, 'isMale': isMale};
  }
}

//2. 객체로 바꾸기 위해서 class를 정의한다.
class HumanDetail {
  String name;
  int age;
  bool isMale;
  List<String> favoriteFoods;
  Contact contact;

  HumanDetail(
      {required this.name,
      required this.age,
      required this.isMale,
      required this.favoriteFoods,
      required this.contact});

//fromJson 네임드 생성자 생성
  HumanDetail.fromJson(Map<String, dynamic> map)
      : this(
            name: map['name'],
            age: map['age'],
            isMale: map['isMale'],
            favoriteFoods: List<String>.from(map['favorite_foods']),//값이름이 받을떄랑 똑같아야한다
            contact: Contact.formJson(map['contact']));// contact 클래서 여기서 바로 객체로 변환
//toJson 생성
  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.formJson 네임드 생성자 만들기
  Contact.formJson(Map<String, dynamic> map)
      : this(mobile: map['mobile'], email: map['email']);

// toJson 메서드 만들기
  Map<String, dynamic> toJson() {
    return {'mobile': mobile, 'email': email};
  }
}