当前位置:网站首页>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

边栏推荐
- socket(2)
- 在每个树行中找最大值[分层遍历之一的扩展]
- dp问题集
- 01--- conditions for interference of two trains of waves at the meeting place
- 多线程收尾
- 机器学习:梯度下降法
- Jianmu continuous integration platform v2.5.0 release
- leetcode1720_2021-10-14
- Datakit agent realizes unified data aggregation in LAN
- A deep learning model for urban traffic flow prediction with traffic events mined from twitter
猜你喜欢
![[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

Datakit agent realizes unified data aggregation in LAN

That is to say, "live broadcast" is launched! One stop live broadcast service with full link upgrade

These map operations in guava have reduced my code by 50%

架构实战营 第 6 期 毕业设计
![在每个树行中找最大值[分层遍历之一的扩展]](/img/5b/81ff20b61c0719ceb6873e44878859.png)
在每个树行中找最大值[分层遍历之一的扩展]

基于 KubeSphere 的分级管理实践

Application practice | massive data, second level analysis! Flink+doris build a real-time data warehouse scheme

socket(1)

Réduire le PIP à la version spécifiée (mettre à jour le PIP avec pycharm avant de le réduire à la version originale)
随机推荐
Opengauss kernel: simple query execution
将二维数组方阵顺时针旋转90°
03--- antireflective film
网络层 && IP
ST表+二分
降低pip到指定版本(通過PyCharm昇級pip,在降低到原來版本)
Kubernetes 集群中流量暴露的几种方案
Reduce the pip to the specified version (upgrade the PIP through CMP and reduce it to the original version)
Collapse code using region
最大流问题
Suspend component and asynchronous component
Implementation of heap sort and quick sort principle
After Firefox drag and drop, Baidu search will always be opened by default. If it is a picture, the picture will be opened.
I really can't do it. After 00, I collapsed and wanted to leave
02--- impossible phenomenon of longitudinal wave
Junior college background, 2 years in Suning, 5 years in Ali. How can I get promoted quickly?
【OpenCV 例程200篇】209. HSV 颜色空间的彩色图像分割
leetcode_1365
[featured] how do you design unified login with multiple accounts?
Several classes of manual transactions
