▩Dart-库概述‘dart:convert’


dart:convert - 编解码JSON,UTF-8等。
dart:convert 库提供 JSON 和 UTF-8 转换器,以及创建其他转换器。 JSON 是一种用于表示结构化对象和集合的简单文本格式。 UTF-8 是一种常见的可变宽度编码,可以表示Unicode字符集中的每个字符。

1. 编解码JSON

使用 jsonDecode() 解码 JSON 编码的字符串为 Dart 对象:

// NOTE: Be sure to use double quotes ("), not single quotes ('), inside the JSON string.
// This string is JSON, not Dart.
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);

使用 jsonEncode() 编码 Dart 对象为 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}]');

只有 int,double,String,bool,null,List 或者 Map 类型对象可以直接编码成 JSON。 List 和 Map 对象进行递归编码。
不能直接编码的对象有两种方式对其编码。第一种方式是:调用 jsonEncode() 时赋值第二个参数,这个参数是一个函数,该函数返回一个能够直接编码的对象。第二种方式是:省略第二个参数,在这种情况下编码器调用对象的 toJson() 方法。

2. 编解码UTF-8字符

使用 utf8.decode() 解码 UTF8 编码的字符创建为 Dart 字符串:

List<int> utf8Bytes = [
  0xc3, 0x8e, 0xc3, 0xb1, 0xc5, 0xa3, 0xc3, 0xa9,
  0x72, 0xc3, 0xb1, 0xc3, 0xa5, 0xc5, 0xa3, 0xc3,
  0xae, 0xc3, 0xb6, 0xc3, 0xb1, 0xc3, 0xa5, 0xc4,
  0xbc, 0xc3, 0xae, 0xc5, 0xbe, 0xc3, 0xa5, 0xc5,
  0xa3, 0xc3, 0xae, 0xe1, 0xbb, 0x9d, 0xc3, 0xb1
];
var funnyWord = utf8.decode(utf8Bytes);
assert(funnyWord == 'Îñţérñåţîöñåļîžåţîờñ');

将 UTF-8 字符串流转换为 Dart 字符串,为 Streamtransform() 方法上指定 utf8.decoder

var lines = utf8.decoder.bind(inputStream).transform(const LineSplitter());
try {
  await for (final line in lines) {
      print('Got ${line.length} characters from stream');
  }
  print('file is now closed');
} catch (e) {
  print(e);
}

使用 utf8.encode() 将 Dart 字符串编码为一个 UTF8 编码的字节流:

List<int> encoded = utf8.encode('Îñţérñåţîöñåļîžåţîờñ');
assert(encoded.length == utf8Bytes.length);
for (int i = 0; i < encoded.length; i++) {
    assert(encoded[i] == utf8Bytes[i]);
}
3. 其他功能

dart:convert 库同样包含 ASCII 和 ISO-8859-1 (Latin1) 转换器。更多详情,参考
API docs for the dart:convert library
JSON Support

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

itzyjr

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值