programing

JSON을 Flutter로 디코딩하는 방법

telebox 2023. 3. 28. 21:34
반응형

JSON을 Flutter로 디코딩하는 방법

JSON을 Flutter로 디코딩하는 방법

질문은 간단하지만, 적어도 나에게는 그렇지 않다.

JSON Strings를 많이 사용하는 프로젝트가 있습니다.기본적으로 앱과 서버 간의 모든 통신은 JSON을 통해 이루어집니다.

사용하고 있습니다.JSON.decode(json_string)오늘 Flutter core(0.5.8-pre.178)를 업데이트 했더니 JSON.decode는 사용할 수 없게 되었습니다.

Flutter Docs에 도움을 요청했는데 JSON.decode를 사용하라고 되어 있어요.

그럼 앞으로 JSON을 Flutter에서 어떻게 풀까요?

Import가 필요합니다.dart:convert:

import 'dart:convert';

인라인 예시

String rawJson = '{"name":"Mary","age":30}';

Map<String, dynamic> map = jsonDecode(rawJson); // import 'dart:convert';

String name = map['name'];
int age = map['age'];

Person person = Person(name, age);

주의: 서버측 Dart의 VS Code에서 이 작업을 수행할 때는 다음 유형을 지정해야 합니다.

Map<String, dynamic> map = jsonDecode(rawJson) as Map<String, dynamic>;

모델 클래스 예시

모델 클래스에는 맵 변환 로직이 포함됩니다.

class Person {
  String name;
  int age;
  Person(this.name, this.age);

  // named constructor
  Person.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        age = json['age'];

  // method
  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'age': age,
    };
  }
 
}

JSON 변환은 다음과 같이 이루어집니다.

String rawJson = '{"name":"Mary","age":30}';
Map<String, dynamic> map = jsonDecode(rawJson);
Person person = Person.fromJson(map);

자세한 내용은 이쪽을 봐 주세요.

시리얼화 코드 생성

시리얼화 코드를 쓸 때 오류가 발생하기 쉬우므로 일반적으로 Dart 팀이 json_serializable 패키지를 사용하는 것이 좋습니다.그러나 다양한 방법의 장단점에 대해서는 여기에서 읽을 수 있습니다.

더 많은 옵션을 원하는 경우 built_value 패키지를 확인할 수도 있습니다.

「 」를 참조해 주세요.

그냥 사용하다

json.decode()

또는

jsonDecode()

다트 2에서는 모든 절규 대소문자가 소문자로 변경되었습니다.

다음 사항을 확인합니다.import 'dart:convert';

를 사용해야 합니다.import 'dart:convert';

디코드:JsonDecoder().convert("$response");

인코딩:JsonEncoder().convert(object)

Json을 이렇게 해독하려면

{
"id":"xx888as88",
"timestamp":"2020-08-18 12:05:40",
"sensors":[
    {
     "name":"Gyroscope",
     "values":[
         {
          "type":"X",
          "value":-3.752716,
          "unit":"r/s"
         },
         {
           "type":"Y",
           "value":1.369709,
           "unit":"r/s"
         },
         {
           "type":"Z",
           "value":-13.085,
           "unit":"r/s"
         }
       ]
    }
  ]
}

저는 이렇게 합니다.

void setReceivedText(String text) {
    Map<String, dynamic> jsonInput = jsonDecode(text);
    
    _receivedText = 'ID: ' + jsonInput['id'] + '\n';
    _receivedText += 'Date: ' +jsonInput['timestamp']+ '\n';
    _receivedText += 'Device: ' +jsonInput['sensors'][0]['name'] + '\n';
    _receivedText += 'Type: ' +jsonInput['sensors'][0]['values'][0]['type'] + '\n';
    _receivedText += 'Value: ' +jsonInput['sensors'][0]['values'][0]['value'].toString() + '\n';
    _receivedText += 'Type: ' +jsonInput['sensors'][0]['values'][1]['type'] + '\n';
    _receivedText += 'Value: ' +jsonInput['sensors'][0]['values'][1]['value'].toString() + '\n';
    _receivedText += 'Type: ' +jsonInput['sensors'][0]['values'][2]['type'] + '\n';
    _receivedText += 'Value: ' +jsonInput['sensors'][0]['values'][2]['value'].toString();
     _historyText = '\n' + _receivedText;
}

나는 Flutter에 처음이니 지금 당장 나를 위해 일해라.

부호화 json.encode() 또는 jsonEncode()

json.decode() 또는 jsonDecode() 디코딩

JSON 인코딩 예시

import 'dart:convert';
 void main() {
 final products = [
 {'id': 1, 'name': 'Product #1'},
 {'id': 2, 'name': 'Product #2'}
 ];
 print(json.encode(products));
}

예: JSON 디코딩

import 'dart:convert';
import 'package:flutter/foundation.dart';

void main() {
 const String responseData =
   '[{"id":1,"name":"Product #1"},{"id":2,"name":"Product #2"}]';

  final products = json.decode(responseData);

  if (kDebugMode) {
   // Print the type of "products"
   print(products.runtimeType);

   // Print the name of the second product in the list
   print(products[1]['name']);
   }
    }

JSON을 디코딩할 수 있습니다.strings,lists그리고.maps오브젝트 또는 오브젝트 리스트에 직접 접속할 수 있습니다.

이것은 패키지로 가능합니다.json_helpers.

import 'package:json_helpers/json_helpers.dart';

예를 들어 다음과 같이 변환할 수 있습니다.String요청 결과(request.body)는, 1개의 메서드만을 호출하는 것으로, 큰 문제 없이 오브젝트 리스트에 직접 액세스 할 수 있습니다.

자세한 예:

String로.Post

  final text = '{"title": "Hello"}';
  final post = text.json((e) => Post.fromJson(e));
  print(post.title);

String로.List<Post>

  final text = '[{"title": "Hello"}, {"title": "Goodbye"}]';
  final post = text.jsonList((e) => Post.fromJson(e));
  print(post[0].title);

Map로.Post

  final map = {"title": "Hello"};
  final post = map.json((e) => Post.fromJson(e));
  print(post.title);

List<Map>로.List<Post>

  final list = [{"title": "Hello"}, {"title": "Goodbye"}];
  final post = list.json((e) => Post.fromJson(e));
  print(post[0].title);

언급URL : https://stackoverflow.com/questions/51601519/how-to-decode-json-in-flutter

반응형