LoginSignup
26
16

More than 5 years have passed since last update.

DartでのJSONのエンコードとデコード

Posted at

docomo Developer supportを運用している@akatsukahaです.

DartでJSONをエンコード/デコードする方法を記載します.DartではJSONをエンコード/デコードするライブラリがdart:convertで提供されています.詳細は,dart:convert - decoding and encoding JSON, UTF-8, and moreを参照してください.以下はDecoding and encoding JSONを和訳し,DartPadですぐ実行出来るように少し修正した内容になっています.


1. JSONのデコードとエンコーディング

1.1. JSONのデコード

jsonDecode()を使用してJSONでエンコードされた文字列をDartオブジェクトにデコードします。

// NOTE: JSONのキーには一重引用符(')ではなく二重引用符(")を利用します.
var jsonString = '''
  [
    {"score": 40},
    {"score": 80}
  ]
''';

var scores = jsonDecode(jsonString);
assert(scores is List);

var firstScore = scores[0];
assert(firstScore is Map);
assert(firstScore['score'] == 40);
実行結果
true
true
true

DartPadで利用する場合は下記をコピペしてください

import 'dart:convert';

void main(){
  // NOTE: JSONのキーには一重引用符(')ではなく二重引用符(")を利用します.
  var jsonString = '''
    [
      {"score": 40},
      {"score": 80}
    ]
  ''';

  var scores = jsonDecode(jsonString);
  print(scores is List);

  var firstScore = scores[0];
  print(firstScore is Map);

  print(firstScore['score'] == 40);
}

1.2. JSONのエンコード

DartオブジェクトをjsonEncode()でJSON形式の文字列にエンコードします。

var scores = [
  {'score': 40},
  {'score': 80},
  {'score': 100, 'overtime': true, 'special_guest': null}
];

var jsonText = jsonEncode(scores);
assert(jsonText ==
    '[{"score":40},{"score":80},'
    '{"score":100,"overtime":true,'
    '"special_guest":null}]');
実行結果
true

DartPadで利用する場合は下記をコピペしてください

import 'dart:convert';

void main(){

  var scores = [
    {'score': 40},
    {'score': 80},
    {'score': 100, 'overtime': true, 'special_guest': null}
  ];

  var jsonText = jsonEncode(scores);
  print(jsonText ==
      '[{"score":40},{"score":80},'
      '{"score":100,"overtime":true,'
      '"special_guest":null}]');
}
26
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
16