【flutter】json的序列化和反序列化,在模型类中序列化json

一,序列化 JSON

1、使用 dart:convert 手动序列化 JSON
2、模型类中序列化 JSON

小项目中使用 dart:convert 手动序列化 JSON 非常好,也非常快速。但是随着项目的增大, dart:convert 手动序列化 JSON 的话失去了大部分静态类型语言特性:类型安全、自动补全和 最重要的编译时异常。这样一来,我们的代码可能会变得非常容易出错。

当我们访问 name 或 email 字段时,我们输入的很快,导致字段名打错了。但由于这个 JSON 在 map 结构中,所以编译器不知道这个错误的字段名。

为了解决上面的问题在大型项目中使用的更多的是在模型类中序列化 JSON。

手动序列化

import 'dart:convert' 

var mapData={"name":"张三","age":"20"}; 

var strData='{"name":"张三","age":"20"}'; 

print(json.encode(mapData)); // Map 转换成 Json 字符串 

print(json.decode(strData)); // Json 字符串转化成 Map 类型

在模型类中序列化 JSON

在线转 https://jsontodart.com/

// '{"_id":"59f6ef443ce1fb0fb02c7a43","title":"笔记本电脑 ","status":"1","pic":"public\\upload\\UObZahqPYzFvx_C9CQjU8KiX.png"," url":"12" }'

class FocusModel {
  String sId;
  String title;
  String status;
  String pic;
  String url;

  FocusModel({this.sId, this.title, this.status, this.pic, this.url});

  FocusModel.fromJson(Map jsonData) {
    this.sId = jsonData["_id"];
    this.title = jsonData["title"];
    this.status = jsonData['status'];
    this.pic = jsonData['pic'];
    this.url = jsonData['url'];
  }
}

使用

@override
  void initState() { 
    super.initState();
     
     var str='{"_id":"59f6ef443ce1fb0fb02c7a43","title":"笔记本电脑 ","status":"1"," url":"12" }';
      
     var focus=new FocusModel.fromJson(json.decode(str));

     print(focus.sId);
     print(focus.title);
  }

项目中使用的例子

接口返回的数据格式

在这里插入图片描述

{
  "result": [
    {
      "_id": "59f6ef443ce1fb0fb02c7a43",
      "title": "笔记本电脑",
      "status": "1",
      "pic": "public\\upload\\UObZahqPYzFvx_C9CQjU8KiX.png",
      "url": "12"
    },
    {
      "_id": "5a012efb93ec4d199c18d1b4",
      "title": "第二个轮播图",
      "status": "1",
      "pic": "public\\upload\\f3OtH11ZaPX5AA4Ov95Q7DEM.png"
    },
    {
      "_id": "5a012f2433574208841e0820",
      "title": "第三个轮播图",
      "status": "1",
      "pic": "public\\upload\\s5ujmYBQVRcLuvBHvWFMJHzS.jpg"
    },
    {
      "_id": "5a688a0ca6dcba0ff4861a3d",
      "title": "教程",
      "status": "1",
      "pic": "public\\upload\\Zh8EP9HOasV28ynDSp8TaGwd.png"
    }
  ]
}

在线 JSON to Dart Model 数据
https://jsontodart.com/

// FocusModel.fromJson(json);
class FocusModel {
  List<FocusItemModel> result;
  FocusModel({this.result});
  FocusModel.fromJson(Map<String, dynamic> json) {
    if (json['result'] != null) {
      result = new List<FocusItemModel>();
      json['result'].forEach((v) {
        result.add(new FocusItemModel.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.result != null) {
      data['result'] = this.result.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class FocusItemModel {
  String sId;
  String title;
  String status;
  String pic;
  String url;

  FocusItemModel({this.sId, this.title, this.status, this.pic, this.url});
  FocusItemModel.fromJson(Map<String, dynamic> json) {
    sId = json['_id'];
    title = json['title'];
    status = json['status'];
    pic = json['pic'];
    url = json['url'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['_id'] = this.sId;
    data['title'] = this.title;
    data['status'] = this.status;
    data['pic'] = this.pic;
    data['url'] = this.url;
    return data;
  }
}

使用

_getFocusData() async{
  var api='http://jd.itying.com/api/focus';

  var res=await Dio().get(api);

  // print(res.data is Map); // true

  var focusList=FocusModel.fromJson(res.data); // 传入 Map 对象,模型类中序列化 JSON
  // print(focusList.result); // 返回 FocusModel 中 result List,List 中的数据为 FocusItemModel

  // focusList.result.forEach((value){
  //   print(value.title);
  //   print(value.pic);
  // });

  setState(() {
    this._focusData= focusList.result;
  });
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值