Flutter string JSON interconversion

Foreword

Recent transfer interface encryption, native iOS case has been transferred through directly to iOS in the Objective-C code is copied to the plug-in package calls flutter, actually took me three days, the problems encountered are basically irrational head circumstances, such as would have been required transmission json string, the result of a direct pass toString () string, the other is the excessive pursuit of code reuse, resulting decision logic is too complex, harder to find bug, try to write code after separation function, Do pursuit of code reuse at the expense of readability of the code, modular functionality

Problems encountered 1:

Use toString()method can convert an object to a string, but lost the quotes and other information, it is no longer a standard JSON, resulting in the server does not properly parse

json into a string

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);
}

Print results

Print object: {name: John Smith, In Email: [email protected] }
Print toString: {name: John Smith, In Email: [email protected] }
Print JSON: { "name": " John Smith", "email" : " [email protected] "}
[Xiaoming, Han Meimei, Hua]
[Xiaoming, Han Meimei, Hua]
[ "Bob", "Han Meimei", "Hua"]

Turn json string

/// 字符串转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);
}

Reproduced in: https: //www.jianshu.com/p/58a86bb75f6b

Guess you like

Origin blog.csdn.net/weixin_33873846/article/details/91181344