关于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~"]); //如没有自动补全的提示,不方面
可以看到,我们这样取值是需要手动的敲字段来获取数据的,一旦字段比较多的话,就很麻烦
// 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 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 data;
CategoryBigListModel(this.data);
factory CategoryBigListModel.fromJson(List json){
return CategoryBigListModel(
json.map((i)=>CategoryBigModel.formJson((i))).toList()
);
}
}
①创建CommonModel 里面有变量、属性
②设置构造方法
③提供工厂方法 fromJson ,里面接收Map类型的json,在里面取出json的值,将它转化成model final类型要return,非则不用
在Android原生开发中,我们有很好用的Gson、FastJson等第三方库来帮助我们将json转成实体类。但是,在Flutter中可能不会有这样的第三方库供我们使用了,详细原因请看 JSON and serialization
https://blog.csdn.net/yuzhiqiang_1993/article/details/88533166
Json数据转成实体类的好处:
将Json数据转成实体类可以方便我们开发的时候使用数据,手动输入字段名称的话很容易出错,并且接口多的话很不好维护。
首先,您需要将字符串解析为更易于管理的 JSON 表示形式。然后,您必须将该表示形式转化为模型或其他一些强类型变量,如此一来,您就可以有效地使用这些字符串。
格式化
http://www.bejson.com/
转换
https://javiercbk.github.io/json_to_dart/
{"code":"0","message":"success","data":[{"image":"http://images.baixingliangfan.cn/compressedPic/20190116145309_40.jpg","oriPrice":2.50,"presentPrice":1.80,"goodsName":"哈尔滨冰爽啤酒330ml","goodsId":"3194330cf25f43c3934dbb8c2a964ade"},{"image":"http://images.baixingliangfan.cn/compressedPic/20190115185215_1051.jpg","oriPrice":2.00,"presentPrice":1.80,"goodsName":"燕京啤酒8°330ml","goodsId":"522a3511f4c545ab9547db074bb51579"},{"image":"http://images.baixingliangfan.cn/compressedPic/20190121102419_9362.jpg","oriPrice":1.98,"presentPrice":1.80,"goodsName":"崂山清爽8°330ml","goodsId":"bbdbd5028cc849c2998ff84fb55cb934"},{"image":"http://images.baixingliangfan.cn/compressedPic/20180712181330_9746.jpg","oriPrice":2.50,"presentPrice":1.90,"goodsName":"雪花啤酒8°清爽330ml","goodsId":"87013c4315e54927a97e51d0645ece76"},{"image":"http://images.baixingliangfan.cn/compressedPic/20180712180233_4501.jpg","oriPrice":2.50,"presentPrice":2.20,"goodsName":"崂山啤酒8°330ml","goodsId":"86388a0ee7bd4a9dbe79f4a38c8acc89"},{"image":"http://images.baixingliangfan.cn/compressedPic/20190116164250_1839.jpg","oriPrice":2.50,"presentPrice":2.30,"goodsName":"哈尔滨小麦王10°330ml","goodsId":"d31a5a337d43433385b17fe83ce2676a"},{"image":"http://images.baixingliangfan.cn/compressedPic/20180712181139_2653.jpg","oriPrice":2.70,"presentPrice":2.50,"goodsName":"三得利清爽啤酒10°330ml","goodsId":"74a1fb6adc1f458bb6e0788c4859bf54"},{"image":"http://images.baixingliangfan.cn/compressedPic/20190121162731_3928.jpg","oriPrice":2.75,"presentPrice":2.50,"goodsName":"三得利啤酒7.5度超纯啤酒330ml","goodsId":"d52fa8ba9a5f40e6955be9e28a764f34"},{"image":"http://images.baixingliangfan.cn/compressedPic/20180712180452_721.jpg","oriPrice":4.50,"presentPrice":3.70,"goodsName":"青岛啤酒11°330ml","goodsId":"a42c0585015540efa7e9642ec1183940"},{"image":"http://images.baixingliangfan.cn/compressedPic/20190121170407_7423.jpg","oriPrice":4.40,"presentPrice":4.00,"goodsName":"三得利清爽啤酒500ml 10.0°","goodsId":"94ec3df73f4446b5a5f0d80a8e51eb9d"},{"image":"http://images.baixingliangfan.cn/compressedPic/20180712181427_6101.jpg","oriPrice":4.50,"presentPrice":4.00,"goodsName":"雪花勇闯天涯啤酒8°330ml","goodsId":"d80462faab814ac6a7124cec3b868cf7"},{"image":"http://images.baixingliangfan.cn/compressedPic/20180717151537_3425.jpg","oriPrice":4.90,"presentPrice":4.10,"goodsName":"百威啤酒听装9.7°330ml","goodsId":"91a849140de24546b0de9e23d85399a3"},{"image":"http://images.baixingliangfan.cn/compressedPic/20190121101926_2942.jpg","oriPrice":4.95,"presentPrice":4.50,"goodsName":"崂山啤酒8°500ml","goodsId":"3758bbd933b145f2a9c472bf76c4920c"},{"image":"http://images.baixingliangfan.cn/compressedPic/20180712175422_518.jpg","oriPrice":5.00,"presentPrice":4.50,"goodsName":"百威3.6%大瓶9.7°P460ml","goodsId":"dc32954b66814f40977be0255cfdacca"},{"image":"http://images.baixingliangfan.cn/compressedPic/20180717151454_4834.jpg","oriPrice":5.00,"presentPrice":4.50,"goodsName":"青岛啤酒大听装500ml","goodsId":"fc85510c3af7428dbf1cb0c1bcb43711"},{"image":"http://images.baixingliangfan.cn/compressedPic/20180712181007_4229.jpg","oriPrice":5.50,"presentPrice":5.00,"goodsName":"三得利金纯生啤酒580ml 9°","goodsId":"14bd89f066ca4949af5e4d5a1d2afaf8"},{"image":"http://images.baixingliangfan.cn/compressedPic/20190121100752_4292.jpg","oriPrice":6.60,"presentPrice":6.00,"goodsName":"哈尔滨啤酒冰纯白啤(小麦啤酒)500ml","goodsId":"89bccd56a8e9465692ccc469cd4b442e"},{"image":"http://images.baixingliangfan.cn/compressedPic/20180712175656_777.jpg","oriPrice":7.20,"presentPrice":6.60,"goodsName":"百威啤酒500ml","goodsId":"3a94dea560ef46008dad7409d592775d"},{"image":"http://images.baixingliangfan.cn/compressedPic/20180712180754_2838.jpg","oriPrice":7.78,"presentPrice":7.00,"goodsName":"青岛啤酒皮尔森10.5°330ml","goodsId":"97adb29137fb47689146a397e5351926"},{"image":"http://images.baixingliangfan.cn/compressedPic/20190116164149_2165.jpg","oriPrice":7.78,"presentPrice":7.00,"goodsName":"青岛全麦白啤11°500ml","goodsId":"f78826d3eb0546f6a2e58893d4a41b43"}]}
import 'package:flutter/material.dart';
import '../service/service_method.dart';
import 'dart:convert';
import '../model/category.dart';
class CategoryPage extends StatefulWidget {
@override
_CategoryPageState createState() => _CategoryPageState();
}
class _CategoryPageState extends State {
@override
Widget build(BuildContext context) {
_getCategory();
return Container(
child:Center(
child: Text('分类页面'),
)
);
}
void _getCategory() async{
var data={
'categoryId':'4',
'CategorySubId':"",
'page':1
};
await request('getMallGoods',formData:data).then((val){
var data=json.decode(val.toString());
print(data);
CategoryListModel list= CategoryListModel.fromJson(data);
// CategoryListModel list= CategoryListModel.fromJson(data['data']);
// list.data.forEach((item)=>print(item));
print('1=============>');
print(list.data[0].goodsName);
});
}
}
// model/category.dart
class CategoryListModel {
String code;
String message;
List data;
CategoryListModel({this.code, this.message, this.data});
CategoryListModel.fromJson(Map json) {
code = json['code'];
message = json['message'];
if (json['data'] != null) {
data = new List();
json['data'].forEach((v) {
data.add(new CategoryData.fromJson(v));
});
}
}
Map toJson() {
final Map data = new Map();
data['code'] = this.code;
data['message'] = this.message;
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class CategoryData {
String image;
double oriPrice;
double presentPrice;
String goodsName;
String goodsId;
CategoryData(
{this.image,
this.oriPrice,
this.presentPrice,
this.goodsName,
this.goodsId});
CategoryData.fromJson(Map json) {
image = json['image'];
oriPrice = json['oriPrice'];
presentPrice = json['presentPrice'];
goodsName = json['goodsName'];
goodsId = json['goodsId'];
}
Map toJson() {
final Map data = new Map();
data['image'] = this.image;
data['oriPrice'] = this.oriPrice;
data['presentPrice'] = this.presentPrice;
data['goodsName'] = this.goodsName;
data['goodsId'] = this.goodsId;
return data;
}
}
携程笔记