Flutter笔记-JSON

89 阅读1分钟

在Flutter中,经常会碰到将服务端json数据解析然后显示到客户端设备界面上,将 JSON 格式的字符串转为 Dart 对象,这个可以通过 dart:convert 中内置的 JSON 解码器json.decode()来实现,该方法可以根据 JSON 字符串具体内容将其转为 List 或 Map,这样我们就可以通过他们来查找所需的值;

demo:

String jsonStr = '[{"name":"Jack"},{"name":"Rose"}]';
List items = json.decode(jsonStr);
print("======>"+items[0]["name"]);
print("======>"+items[1]["name"]);
String jsonStr2 = '{"name":"Jack","email":"test@example.com"}';
Map<String,dynamic> user  = json.decode(jsonStr2);
print('Howdy, ${user['name']}!');
print('We sent the verification link to ${user['email']}.');

demo2

import 'dart:convert';
class Demo {
   final String desc;
   final int id;
   final String name;
   Demo({
     required this.desc,
     required this.id,
     required this.name});
   factory Demo.fromJson(Map<String,dynamic> json) {
     return Demo(desc: json['desc'], id: json['id'], name: json['name']);
   }
   Map<String,dynamic> toJson() {
     return {
       'desc':desc,
       'id':id,
       'name':name
     };
   }

}

void main() {
  print("================>>>> start");
  String jsonResult = '{"desc": "天气不错", "id": 30, "name": "宝宝巴士"}';
  Map<String,dynamic> jsonMap = json.decode(jsonResult);
  var demo = Demo.fromJson(jsonMap);
  print("========>>>>${demo.name}");

  String jsonPlay = json.encode(demo);
  print("======>>> Content:$jsonPlay");
}

也可以直接用插件库:json_serializable