FlutterJsonBeanFactory)的,网上的教程看着有点懵,并且没有说明大概原理以及如何正确完整的使用!!! 所以经过自己的实践,做个总结和分享吧!
Let's do it! Android Studio开发环境哈,其他开发环境,用法应该类似的吧!
1. 安装插件,然后重启一下AS
2.
2.1
2.2 用法
String jsonData = "自己把json字符放这,或者请求https://jsonplaceholder.typicode.com/posts接口获取response.data也行";
List<dynamic> planListObj = json.decode(jsonData);
List<PlanListDataEntity> planListData =
planListObj.map((e) {
return PlanListDataEntity().fromJson(e);
}).toList();
关键:return PlanListDataEntity().fromJson(e). 一次看跟过去的截图
差不多就是这样的流程。
后面你可能需要包装一下请求,以便于适应各种数据结构(列表,对象,字符串等)。
我目前为了针对这种情况,想起来Java那种方式,所以解析采用了对象,对象列表的方式(由于泛型确实感觉不那么好用,所以曲线了一把):
import 'json_factory.dart';
class HttpResponseEntity<T>{
int code;
String msg;
T data;
HttpResponseEntity({this.code, this.msg, this.data});
HttpResponseEntity.fromJson(Map<String, dynamic> jsonData) {
msg = (null == jsonData['msg']) ? "" : jsonData['msg'];
code = (null == jsonData['code']) ? -1 : jsonData['code'];
data = jsonData['data'] != null ? EntityFactory.generateOBJ<T>(jsonData['data']) : null;
}
}
class HttpResponseListEntity<T>{
int code;
String msg;
List<T> data;
HttpResponseListEntity({this.code, this.msg, this.data});
HttpResponseListEntity.fromJson(Map<String, dynamic> jsonData) {
msg = (null == jsonData['msg']) ? "" : jsonData['msg'];
code = (null == jsonData['code']) ? -1 : jsonData['code'];
if (jsonData['data'] != null) {
data = new List<T>();
(jsonData['data'] as List).forEach((element){
data.add(EntityFactory.generateOBJ<T>(jsonData['data']));
});
}
}
}
而EntryFactory如下:
import 'package:flutter_app2/pages/home/model/plan_list_data_entity.dart';
/// 由于不能像Java那样创建泛型对象
/// 这里负责根据类型动态创建实例对象
class EntityFactory {
static T generateOBJ<T>(json) {
if (T.toString() == "PlanListDataEntity") {
return PlanListDataEntity().fromJson(json) as T;
} else {
return null;
}
}
}
其实还蛮有意思的妮。。。先这样。。我觉得这些插件感觉有点麻烦了。。不知道为什么,习惯了简单的方式。我觉得可以直接在线转换算了。。哈哈。。