본문 바로가기
Dart (Flutter)

[Dart] Handling JSON

by llHoYall 2022. 3. 12.

Dart supports handling JSON.

You need to import convert library.

Decoding JSON String

jsonDecode() method converts JSON string into List that is dynamic type.

import 'dart:convert';

void main() {
  var jsonString = '''
    [{"key1": "value1"}, {"key2": "value2"}]
  ''';
  var decodedString = jsonDecode(jsonString);

  print(decodedString is List);     // true
  print(decodedString[0]);          // {key1: value1}
  print(decodedString[0] is Map);   // true
  print(decodedString[1]["key2"]);  // value2
}

Encoding to JSON String

jsonEncode() method converts List data into JSON string.

import 'dart:convert';

void main() {
  var jsonData = [
    {"key1": "value1"},
    {"key2": "value2"}
  ];
  var encodedString = jsonEncode(jsonData);

  print(encodedString);  
  // [{"key1":"value1"},{"key2":"value2"}]
}

댓글