一、内联反序列化
把JSON字符串转换成 Map<String, dynamic> 或者 List<dynamic>
import 'dart:convert'; main(List<String> args) { JsonCodec json = new JsonCodec(); String str = '{"name":"tom"}'; Map<String, dynamic> a = json.decode(str); print(a["name"]); String str1 = '["a","b"]'; List<dynamic> b = json.decode(str1); print(b.length); String str3 = '{"name": "John Smith","email": "john@example.com"}'; var c = json.decode(str3); print(c.runtimeType); //Map<String, dynamic> String str4 = '{"name": "John Smith","email": ["a","b"]}'; var d = json.decode(str4); print(d.runtimeType); //Map<String, dynamic> String str5 = '{"name": "John Smith","email": {"a":"o","b":"p"}}'; var e = json.decode(str5); print(e.runtimeType); //<String, dynamic> // String str6 = '{"name": "John Smith","email": {"a","b"}}'; // var f = json.decode(str6); //FormatException: Unexpected character 报错 // print(e.runtimeType); }
复杂些的比如
'{"age":19,"name":["tom","liu","wu"]}' ??
二、把字符串转成类对象
import 'dart:convert'; main(List<String> args) { String str = '{"age":19,"name":"tom"}'; Map map = jsonDecode(str); Student user = Student.ds(map); print(user.age); } class Student { int age; String name; //Student(this.age, this.name); Student.ds(Map<String, dynamic> json) : age = json['age'], name = json['name']; }
三、自动反序列化
使用 json_serializable https://pub.dev/packages/json_serializable