Bootstrap

Flutter 中 json 字符串与 Map 相互转化

前言

近期项目从 OC 转 Flutter 过程中,接口调用返回数据时 json 字符串转 Map。总结一下:

遇到的问题:

使用 toString() 方法能将对象转换成字符串,但是会丢失引号等信息,不再是标准 JSON,导致服务端解析不正常

json转换为字符串
import 'dart:convert' as convert;
/// json转换为字符串
void testJson2String(){
  var user = { "name": "John Smith", "email": "[email protected]"};
  String jsonString = convert.jsonEncode(user);
  String normalString2 = user.toString();
  print('打印对象: $user');
  print('打印toString: $normalString2');
  print('打印JSON: $jsonString');
  var nameList = ["小明","韩梅梅","李华"];
  String normalNameString = nameList.toString();
  String josnNameString = convert.jsonEncode(nameList);
  print(nameList);
  print(normalNameString);
  print(josnNameString);
}
打印结果

打印对象: {name: John Smith, email: [email protected]}
打印toString: {name: John Smith, email: [email protected]}
打印JSON: {"name":"John Smith","email":"[email protected]"}
[小明, 韩梅梅, 李华]
[小明, 韩梅梅, 李华]
["小明","韩梅梅","李华"]
字符串转json
/// 字符串转json
void testString2Json(){
  var jsonTxt1 = '{ "name": "John Smith", "email": "[email protected]"}';
  Map<String, dynamic> user = convert.jsonDecode(jsonString1);
  var jsonTxt2 = '["小明","韩梅梅","李华"]';
  List nameList = convert.jsonDecode(jsonTxt2);
}
;