• 카테고리

    질문 & 답변
  • 세부 분야

    모바일 앱 개발

  • 해결 여부

    해결됨

4장 Travia를 이용해서 다른 api에 적용 한줄 가져오려고합니다.

23.09.04 22:06 작성 23.09.04 23:06 수정 조회수 275

1

  Future<String> getNumberTrivia() async {
    // get 메소드로 URL 호출
    Response result = await Dio().get('https://api.adviceslip.com/advice');
    var trivia = result.data['advise']; // 응답 결과 가져오기
    print(trivia);
    return trivia;

4장 Travia를 응용해서

Json 원본 .. {"slip": { "id": 65, "advice": "When having a clear out"} //한줄 나오는데 분해가 안되네요...

두번째 값 문장만 가져 오려면 어떻게 해야하나요?" 이것도 json decode 해야하나요.

"When having a clear out"

 

 ./.....

Response result = await Dio().get('https://api.adviceslip.com/advice',
        queryParameters: {"slip": "advice"},);

//이해를 못한건지 .. 
쿼리를 넣엇는데 print {"slip": { "id": 224, "advice": "Don't drink bleach."}}
    Response result = await Dio().get('https://api.adviceslip.com/advice');
    final trivia = result.data; // 응답 결과 가져오기
    Map<String, dynamic> user = jsonDecode(trivia);
    print(user.runtimeType);
    print(user["slip"]);
    return trivia;

 _JsonMap

{id: 46, advice: Try going commando to an important meeting, NB: don't wear a skirt.}

 

    print(user["advice"]);   

 _JsonMap

Null

 

 

  {
    "slip": {
      "slip_id": "2",
       "advice": "Smile and the world smiles with you. Frown and you're on your own."
    }
  }
  

답변 1

답변을 작성해보세요.

2

안녕하세요.

다음과 같은 응답을 반환하는 API에서 advice만 추출하는 방법을 알려드립니다.

{"slip": { "id": 117, "advice": "A common regret in life is wishing one hadn't worked so hard."}}

일단 최종 결과는 아래에 있는 getAdvice() 함수를 사용하면 advice 값만 뽑아오실 수 있습니다.

import 'dart:convert';

import 'package:dio/dio.dart';

void main() async {
  final advice = await getAdvice();
  print(advice); /// 최종 결과 : A common regret in life is wishing one hadn't worked so hard.
}

Future<String> getAdvice() async {
  final result = await Dio().get('https://api.adviceslip.com/advice');

  /// json format을 따르는 String
  final stringData = result.data;

  /// Map<String, dynamic>
  final data = jsonDecode(stringData);

  final advice = data['slip']['advice'];
  return advice;
}

강의에서 진행한 샘플 API에선 jsonDecode()를 직접 안해도 바로 접근이 가능했었는데, 위의 경우에는 jsonDecode()를 직접 명시해야 접근이 가능하여 헷갈리셨을 것 같습니다.

Dio는 API의 응답의 헤더(header) 영역에 content-typeapplication/json이라고 명시되어 있으면 자동으로 jsonDecode() 함수를 실행한 값을 반환하고 그렇지 않은 경우 문자열로 반환합니다.

헤더에 들어있는 값은 다음과 같이 확인할 수 있는데, 위 API는 content-typetext/html으로 넘어오고 있기에 단순 문자열로 넘어오게 됩니다. 따라서 jsonDecode()를 별도로 실행해 주셔야하고, 그 결과 Map<String, dynamic> 형태로 데이터를 다룰 수 있습니다.

final result = await Dio().get('https://api.adviceslip.com/advice');
print(result.headers);

문자열을 Map으로 변경하신 뒤 advice에 접근하기 위해선 먼저 slip 이라는 key로 advice가 속해있는 Map을 data['slip']이라고 명시하여 가져오고, 이후에 data['slip']['advice']라고 명시하여 advice를 가져오실 수 있습니다.

읽어보시고 설명이 더 필요하신 부분 있으면 언제든지 문의 남겨주세요
감사합니다 :)

 

정말 감사합니다 . 혼자서는 하루 종일 구글링 해도 모르겠더군요 .

^^)b 감사합니다. 선생님