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

时间:2025-03-31 20:00:53

前言

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

遇到的问题:

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

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


打印结果

打印对象: {name: John Smith, email: john@}
打印toString: {name: John Smith, email: john@}
打印JSON: {"name":"John Smith","email":"john@"}
[小明, 韩梅梅, 李华]
[小明, 韩梅梅, 李华]
["小明","韩梅梅","李华"]


字符串转json
/// 字符串转json
void testString2Json(){
  var jsonTxt1 = '{ "name": "John Smith", "email": "john@"}';
  Map<String, dynamic> user = (jsonString1);
  var jsonTxt2 = '["小明","韩梅梅","李华"]';
  List nameList = (jsonTxt2);
}