文章目录
手动序列化 JSON
关于json.decode(string) ,可以将Json字符串转化成Map类型
缺点:类型安全、没有自动补全、编译时会有异常
import 'dart:convert';
var str='{"name":"李四",“age”:20}';
var result=json.decode(str); // Json字符串转化成Map类型
print(result["age"]); // 如str字符串age是数字/字符串类型,打印出来还是20,存在类型安全
print(result["name~"]); //如没有自动补全的提示,不方面
可以看到,我们这样取值是需要手动的敲字段来获取数据的,一旦字段比较多的话,就很麻烦
通过泛类型序列化Json
// model/FocusModel.dart
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.xxx=xxx
this.sId = jsonData["_id"];
this.title = jsonData["title"];
this.status = jsonData['status'];
this.pic = jsonData['pic'];
this.url = jsonData['url'];
}
}
// 使用
把json字符串转化为map类型,然后把它序列化(FocusModel.fromJson),就可以通过focus.xxx直接获取数据
import '../model/FocusModel.dart';
import 'dart:convert';
var str='{"_id":"1","title":"电脑 ","status":"1"," url":"12" }'; // 可以省略new
var focus=new FocusModel.fromJson(json.decode(str));
print(focus.sId);
print(focus.title);
另一个例子:
将map转换model
class CategoryBigModel{
String mallCategoryId;//类别编号
String mallCategoryName;//类别名称
List<dynamic> bxMallSubDto;//不知道具体模型就用dynamic类型 ( dynamic 动态类型 )
Null comments;
String image;
//构造方法
CategoryBigModel({
this.mallCategoryId,
this.mallCategoryName,
this.bxMallSubDto,
this.comments,
this.image
});
//工厂类的构造方法,就是我常用的实例化对象模式,好处是我们调用这个类的时候不用再使用new关键字了
//相当于java里面的多态,用起来和我们的静态方法是一样的
factory CategoryBigModel.formJson(dynamic json){
return CategoryBigModel(
mallCategoryId:json['mallCategoryId'],
mallCategoryName:json['mallCategoryName'],
bxMallSubDto:json['bxMallSubDto'],
comments:json['comments'],
image:json['image']
);
}
}
//列表的model
class CategoryBigListModel{
List<CategoryBig