반응형
1. JSON 응답 타입을 확인 하자
2. JSON Object Type 의 이해 (동기적 방식 처리)
3. JSON Array Type 의 이해 (동기적 방식 처리)

 

 

1. JSON 응답 타입을 확인 하자 - Resposne → body(String)

// Json Object type -> { "key" : "value"}
// Json Array type -> [{},{},{} ]

 

 

Todo DTO

// TODO : DTO 개념 클래스를 설계할 때 nullable 타입으로 설계하자

class Todo {
  int? userId;
  int? id;
  String? title;
  bool? completed;

  // 기본 생성자
  // 강제성 - 생성자
  Todo(this.userId, this.id, this.title, this.completed);

  // 명명된 생성자2 - Map을 넣으면 Todo 오브젝트가 반환되는 코드를 작성
  // 이니셜 라이져 (변수를 초기화 해주는 문법)
  Todo.fromJson(Map<String, dynamic> json)
      : userId = json['userId'],
        id = json['id'],
        title = json['title'],
        completed = json['completed'];

  @override
  String toString() {
    return '내가 보는 - Todo{userId: $userId, id: $id, title: $title, completed: $completed}';
  }
}

 

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:dart_future_v1/todo.dart';

void main() async {
  var res = await fetchTodo();

  if (res.statusCode == 200) {
    print("통신 성공");
    Map<String, dynamic> result = json.decode(res.body);
    var todo1 = Todo.fromJson(result);

    print("title : ${todo1.title} ");
    print("completed : ${todo1.completed} ");
  } else {
    print("통신 실패");
  }
}

// 통신을 하는 함수 만들어 보기
Future<http.Response> fetchTodo() async {
  const url = 'https://jsonplaceholder.typicode.com/todos/1';

  final response = await http.get(Uri.parse(url));

  return response;
}

 

실행결과

통신 성공
title : delectus aut autem 
completed : false 

Process finished with exit code 0

 

 

이번에는 user 정보를 파싱해서 출력해보자.

 

 

User.dart

// TODO : DTO 개념 클래스를 설계할 때 nullable 타입으로 설계하자

import 'address.dart';
import 'company.dart';

class User {
  int? id;
  String? name;
  String? username;
  String? email;
  Address? address;
  String? phone;
  String? website;
  Company? company;

  User(this.id, this.name, this.username, this.email, this.address, this.phone,
      this.website, this.company);

  User.fromJson(Map<String, dynamic> json)
      : id = json['id'],
        name = json['name'],
        username = json['username'],
        email = json['email'],
        address = json['address'] != null ? Address.fromJson(json['address']) : null,
        phone = json['phone'],
        website = json['website'],
        company = json['company'] != null ? Company.fromJson(json['company']) : null;

  @override
  String toString() {
    return 'User{id: $id, name: $name, username: $username, email: $email, address: $address, phone: $phone, website: $website, company: $company}';
  }
}

 

 

address.dart

import 'geo.dart';

class Address {
  String? street;
  String? suite;
  String? city;
  String? zipcode;
  Geo? geo;

  Address({this.street, this.suite, this.city, this.zipcode, this.geo});

  Address.fromJson(Map<String, dynamic> json)
      : street = json['street'],
        suite = json['suite'],
        city = json['city'],
        zipcode = json['zipcode'],
        geo = json['geo'] != null ? Geo.fromJson(json['geo']) : null;

  @override
  String toString() {
    return 'Address{street: $street, suite: $suite, city: $city, zipcode: $zipcode, geo: $geo}';
  }
}

 

geo.dart

class Geo {
  String? lat;
  String? lng;

  Geo({this.lat, this.lng});

  Geo.fromJson(Map<String, dynamic> json)
      : lat = json['lat'],
        lng = json['lng'];

  @override
  String toString() {
    return 'Geo{lat: $lat, lng: $lng}';
  }
}

 

 

main.dart

import 'dart:convert';

import 'package:dart_future_v1/user.dart';
import 'package:http/http.dart' as http;

void main() async {


  var res = await fetchUser();

  if(res.statusCode == 200) {
    print("통신 성공");
    Map<String, dynamic> result = json.decode(res.body);
    var user1 = User.fromJson(result);

    print("id : ${user1.id} ");
    print("name : ${user1.name} ");
    print("username : ${user1.username} ");
    print("email : ${user1.email} ");
    print("address : ${user1.address} ");
    print("phone : ${user1.phone} ");
    print("website : ${user1.website} ");
    print("company : ${user1.company} ");


  } else {
    print("통신 실패");
  }





}


// 통신을 하는 함수 만들어 보기
Future<http.Response> fetchUser() async {
  const url = 'https://jsonplaceholder.typicode.com/users/1';

  final response = await http.get(Uri.parse(url));

  return response;
}

 

 

실행결과


C:/devtool/flutter/bin/cache/dart-sdk/bin/dart.exe --enable-asserts C:\devtool\class_flutter\dart_future_v1\lib\main11.dart
통신 성공
id : 1 
name : Leanne Graham 
username : Bret 
email : Sincere@april.biz 
address : Address{street: Kulas Light, suite: Apt. 556, city: Gwenborough, zipcode: 92998-3874, geo: Geo{lat: -37.3159, lng: 81.1496}} 
phone : 1-770-736-8031 x56442 
website : hildegard.org 
company : Company{name: Romaguera-Crona, catchPhrase: Multi-layered client-server neural-net, bs: harness real-time e-markets} 

Process finished with exit code 0
반응형

'Flutter' 카테고리의 다른 글

TodoList App 만들기  (0) 2024.03.21
Flutter MVVM 패턴 - 1  (0) 2024.03.19
dart 비동기 프로그래밍 - 2  (0) 2024.03.15
dart 비동기 프로그래밍 -1  (0) 2024.03.14
블로그 웹 앱 만들어보기  (0) 2023.12.15

+ Recent posts