网上有好多json转对象的方法: 在线生成的:https://javiercbk.github.io/json_to_dart/ 弊端:每次都要打开网页去生成,尤其是公司网不好的时候,急死;
插件生成的:插件名:FlutterJsonBeanFactory 弊端:不知道没弄明白还是根本没法设置,我只想要一个简单的文件,不要什么继承. 因为子类型总是重复生成.
以下我自己解析json内容生成对象
只涉及到自己用到的类型,如有其他,读者可随时更改
import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('生成实体数据', () async {
String filePath = "lib/model"; // 生成目录,不带/后缀
String libraryName = "models"; // 模块名称
String jsonFile = "models.json"; // json文件
String entitySuffix = "Entity"; // 实体后缀
String childTypeFieldName = "_"; // 集合对象,依据对象中的哪个字段获取子类型
List<Type> constTypes = [String, int, double]; // 常量类型,这些集合类型不做子类处理
File libraryFile = File("$filePath/index.dart");
await libraryFile.parent.create();
String jsonData = await File(jsonFile).readAsString();
Map<String, dynamic> entities = json.decode(jsonData);
String parts = "library $libraryName;\n"; // index.dart内容
for (String fileName in entities.keys) {
String entityName = fileName; // 实体名称
String entityContent = "part of $libraryName;\n\n";
if (entityName.contains("_")) {
String en = "";
for (String pre in entityName.split("_")) {
en += pre.substring(0, 1).toUpperCase() + pre.substring(1);
}
entityName = en;
}
entityName =
entityName.substring(0, 1).toUpperCase() + entityName.substring(1);
entityName += entitySuffix;
parts += "\npart '$fileName.dart';";
entityContent += "class $entityName{\n";
Map<String, dynamic>? entityData = entities[fileName];
String fields = "";
String mapToKey = "";
String keyToMap = "";
for (String entityKey in entityData!.keys) {
Type type = entityData[entityKey].runtimeType;
Type? childType;
String typeName = "$type";
String childTypeName = "";
if (type == List) {
// 集合类型提取泛型
childType = entityData[entityKey][0].runtimeType;
if (constTypes.contains(childType)) {
typeName = "List<$childType>";
} else {
childTypeName =
entityData[entityKey][0][childTypeFieldName] + entitySuffix;
// 使用id做子类型
typeName = "List<$childTypeName>";
}
}
entityContent += " $typeName? $entityKey;\n"; // 定义变量
fields += " this.$entityKey,\n";
if (childType == null) {
mapToKey += "\n $entityKey = json[\"$entityKey\"];";
} else if (constTypes.contains(childType)) {
mapToKey += "\n $entityKey = json[\"$entityKey\"];";
} else {
mapToKey += """\n
if (json["$entityKey"] != null) {
$entityKey = [];
json['$entityKey'].forEach((v) {
$entityKey!.add($childTypeName.forJson(v));
});
}\n""";
}
if (childType == null) {
keyToMap += "\n data['$entityKey'] = $entityKey;";
} else if (constTypes.contains(childType)) {
keyToMap += "\n data['$entityKey'] = $entityKey;";
} else {
keyToMap += """\n
if($entityKey != null) {
data['$entityKey'] = $entityKey!.map((v) => v.toJson()).toList();
}\n""";
}
}
// 构造函数
entityContent += "\n $entityName({\n$fields });\n\n";
// json转对象
entityContent +=
" $entityName.forJson(Map<String,dynamic> json) {$mapToKey\n }\n\n";
// 对象转json
entityContent +=
" Map<String,dynamic> toJson(){\n final Map<String,dynamic> data = {};$keyToMap\n return data;\n }\n}";
File entityFile = File("$filePath/$fileName.dart");
if (!await entityFile.exists()) {
entityFile.createSync();
} else {
print("重写:$entityFile");
}
IOSink out = entityFile.openWrite();
out.write(entityContent);
await out.close();
}
IOSink out = libraryFile.openWrite();
out.write(parts);
out.close();
});
}
json格式如下
{
"category_type": {
"id": "",
"name": "分类菜单",
"children": [
{
"id": "CategoryType"
}
]
},
"category": {
"id": "",
"categoryId": "",
"name": "",
"color": "",
"image": "",
"url": "deeplink"
},
}
生成结果
index.dart category_type.dart category.dart
备注说明
1.子数据类型用子数据的_(下划线)值代替 2.有些类型转为json对象时不需要对象转化,有变量constTypes控制,加入即可.
|