当前位置:网站首页>Flutter 如何使用在线转码工具将 JSON 转为 Model
Flutter 如何使用在线转码工具将 JSON 转为 Model
2022-06-24 19:30:00 【一叶飘舟】
国内大佬CrazyCodeBoy提供的工具:
正文开始。
目标 json:
{
"posts": [
{
"id": "0",
"created": 1590453935992,
"content": "提供基于GraphQL API的数据查询及访问,「Hasura」获990万美元A轮..."
},
{
"id": "1",
"created": 1590453935992,
"content": "为什么GraphQL是API的未来"
},
{
"id": "2",
"created": 1590453935992,
"content": "Netflix:我们为什么要将 GraphQL 引入前端架构?"
}
]
}
打开 quicktype 网站(可能需要科学访问网络):Instantly parse JSON in any language | quicktype

点击右上角 Options 按钮,并作如下配置:

粘贴 JSON 到输入框中,并在左上角输入模型名称 PostsData:

右侧会自动生成模型:

复制右侧代码,创建相关类型:
/lib/PostsData.dart:
// To parse this JSON data, do
//
// final postsData = postsDataFromJson(jsonString);
import 'dart:convert';
class PostsData {
final List<Post> posts;
PostsData({
this.posts,
});
factory PostsData.fromJson(String str) => PostsData.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory PostsData.fromMap(Map<String, dynamic> json) => PostsData(
posts: json["posts"] == null ? null : List<Post>.from(json["posts"].map((x) => Post.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"posts": posts == null ? null : List<dynamic>.from(posts.map((x) => x.toMap())),
};
}
class Post {
final String id;
final int created;
final String content;
Post({
this.id,
this.created,
this.content,
});
factory Post.fromJson(String str) => Post.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Post.fromMap(Map<String, dynamic> json) => Post(
id: json["id"] == null ? null : json["id"],
created: json["created"] == null ? null : json["created"],
content: json["content"] == null ? null : json["content"],
);
Map<String, dynamic> toMap() => {
"id": id == null ? null : id,
"created": created == null ? null : created,
"content": content == null ? null : content,
};
}
完成,Good Job!
其他在线转换工具
一. 在线生成网站:
https://javiercbk.github.io/json_to_dart/
二. JsonToDart 插件【推荐】
在 Android Studio 中安装 JsonToDart 插件,
a.打开 Preferences(Mac)或者 Setting(Window),
b.选择 Plugins,搜索 JsonToDart
点击 Install(上图已经安装),安装完成后重启即可
选定目录,点击右键,选择 New->Json to Dart
将json字符串复制进去,填写类明后,点击Generate按钮即可
附快捷键:
Windows:ALT + Shift + D
Mac:Option + Shift + D
- 在pubspec.yaml中添加依赖
json_annotation: ^3.1.0 json_serializable: ^3.5.0 build_runner: ^1.0.0

在Android Stuido中执行Pub get
- 新建模型类(mode/demo_model.dart)
class DemoModel{
}- 在网页上把后端请求到的JSON数据转换成Model:
https://czero1995.github.io/json-to-model/:网站转换支持无限层次嵌套复杂对象的转换

- 比如将以下JSON数据复制到网页上(左边):
{
"code": 0,
"data": {
"avatar": "xxx.png",
"id": 7,
"float":0.1,
"is_deleted": false,
"nickname": "nickName",
"openId": null,
"phone": "13641418383",
"store_ids": [1,2],
"updated": "2020-11-05 11:53:10",
"more":[{"a":1,"b":"b","c":{"c1":0.2,"c2":2}}]
}
}- 然后转换成Model数据(右边)
import 'package:json_annotation/json_annotation.dart';
part 'demo_model_data.g.dart';
@JsonSerializable(explicitToJson: true)
class DemoModelModel {
DemoModelData data;
DemoModelModel({
this.data,
this.code,
this.message
});
factory DemoModelModel.fromJson(Map<String, dynamic> json) => _$DemoModelModelFromJson(json);
Map<String, dynamic> toJson() => _$DemoModelModelToJson(this);
}
@JsonSerializable(explicitToJson: true)
class DemoModelData {
String avatar;
int id;
double float;
bool is_deleted;
String nickname;
var openId;
String phone;
List<int> store_ids;
String updated;
List<MoreData> more;
DemoModelData({
this.avatar,
this.id,
this.float,
this.is_deleted,
this.nickname,
this.openId,
this.phone,
this.store_ids,
this.updated,
this.more,
});
factory DemoModelData.fromJson(Map<String, dynamic> json) => _$DemoModelDataFromJson(json);
Map<String, dynamic> toJson() => _$DemoModelDataToJson(this);
}
@JsonSerializable(explicitToJson: true)
class MoreData{
int a;
String b;
CData c;
MoreData({
this.a,
this.b,
this.c,
});
factory MoreData.fromJson(Map<String, dynamic> json) => _$MoreDataFromJson(json);
Map<String, dynamic> toJson() => _$MoreDataToJson(this);
}
@JsonSerializable(explicitToJson: true)
class CData{
double c1;
int c2;
CData({
this.c1,
this.c2,
});
factory CData.fromJson(Map<String, dynamic> json) => _$CDataFromJson(json);
Map<String, dynamic> toJson() => _$CDataToJson(this);
}再将转换之后的数据复制出来覆盖到demo_model.dart文件上
- 执行build_runner
在项目终端下执行命令:
flutter pub run build_runner build
执行完成后,会生成demo_model.g.dart文件
整个执行流程如下(打开下面链接查看)
https://image-static.segmentfault.com/305/532/3055326920-21e28cc64f409c11
JSON to Dart Converter - Convert JSON Code Online

边栏推荐
- 【吴恩达笔记】多变量线性回归
- [featured] how do you design unified login with multiple accounts?
- Cannot find reference 'imread' in 'appears in pycharm__ init__. py‘
- 如何化解35岁危机?华为云数据库首席架构师20年技术经验分享
- Direct attack on "three summers" production: good harvest news spreads frequently and summer broadcasting is in full swing
- 壹沓科技签约七匹狼,助力「中国男装领导者」数字化转型
- Network layer & IP
- leetcode_1365
- 好想送对象一束花呀
- Vscode netless environment rapid migration development environment (VIP collection version)
猜你喜欢

How to refine permissions to buttons?
![[200 opencv routines] 209 Color image segmentation in HSV color space](/img/fa/9a40015cbcf9c78808f147e510be4c.jpg)
[200 opencv routines] 209 Color image segmentation in HSV color space

基于 KubeSphere 的分级管理实践

应用实践 | 海量数据,秒级分析!Flink+Doris 构建实时数仓方案

平衡二叉搜索树

将二维数组方阵顺时针旋转90°

面试官:你说你精通Redis,你看过持久化的配置吗?

leetcode-201_ 2021_ 10_ seventeen
![[theory] deep learning in the covid-19 epic: a deep model for urban traffic revitalization index](/img/d9/f5461a81a343f3c3ca01876e423fa2.png)
[theory] deep learning in the covid-19 epic: a deep model for urban traffic revitalization index

I really can't do it. After 00, I collapsed and wanted to leave
随机推荐
是真干不过00后,给我卷的崩溃,想离职了...
【无标题】
壹沓科技签约七匹狼,助力「中国男装领导者」数字化转型
LeetCode-513. Find the value in the lower left corner of the tree
ST表+二分
[untitled]
堆排序和快速排序原理实现
[notes of wuenda] fundamentals of machine learning
How to resolve the 35 year old crisis? Sharing of 20 years' technical experience of chief architect of Huawei cloud database
Network layer & IP
TKKC round#3
openGauss内核:简单查询的执行
leetcode_ 191_ 2021-10-15
Drag drag drag
socket done
How to achieve energy conservation and environmental protection of full-color outdoor LED display
Minimum spanning tree based on Kruskal
二叉搜索树模板
Practice of hierarchical management based on kubesphere
最大流问题
