API参考:dart:convert library

引入:

  1. import 'dart:convert';

一、json

将字符串转换为对象:

  1. import 'dart:convert' show json;
  2. var jsonString = '''
  3. [
  4. {"score": 40},
  5. {"score": 80}
  6. ]
  7. ''';
  8. var scores = json.decode(jsonString);
  9. assert(scores is List);
  10. assert(scores[0] is Map);
  11. assert(firstScore['score'] == 40);
  12. print(scores); // [{score: 40}, {score: 80}]

将对象转换为字符串:

  1. var scores = [
  2. {'score': 40},
  3. {'score': 80},
  4. ];
  5. var jsonText = json.encode(scores);
  6. print(jsonText); // [{"score":40},{"score":80}]
  • json.decode 可以写为 jsonDecode
  • json.encode 可以写为 jsonEncode

二、utf8

使用 utf8.encodeutf8.decode 编码和解码数据:

  1. import 'dart:convert' show utf8;
  2. var str = 'Hello world';
  3. var strEncode = utf8.encode(str);
  4. print(strEncode); // [72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
  5. print(strEncode is List<int>); // true
  6. var strDecode = utf8.decode(strEncode);
  7. print(strDecode == str); // true