本文共 2009 字,大约阅读时间需要 6 分钟。
使用Flutter&Dart已经快两个季度了,期间参与了Flutter插件的开发、Flutter Tools开发、Flutter热修复以及内部使用Flutter for Web等的实践。这里简单推荐下一个Flutter的Json和Bean的互转流程。
比如我们使用一言官网的开放API——,获取一个JSON。
{ "id": 841, "hitokoto": "不论生死,好坏,对错;只要载入史册那就代表胜利——历史由胜者书写", "type": "f", "from": "网络", "from_who": null, "creator": "hitokoto", "creator_uid": 1775, "reviewer": 0, "uuid": "56827477-4c50-4eab-bfdc-e21c0f02a59f", "created_at": "1478787580"}
拿到Json之后,我们可以使用这个工具,复制Json到左边的输入框,输入名称OneSentence
,点击Generate Dart即可生成我们需要的Bean类。
OneSentence.dart
class OneSentence { int id; String hitokoto; String type; String from; Null fromWho; String creator; int creatorUid; int reviewer; String uuid; String createdAt; OneSentence( {this.id, this.hitokoto, this.type, this.from, this.fromWho, this.creator, this.creatorUid, this.reviewer, this.uuid, this.createdAt}); OneSentence.fromJson(Mapjson) { id = json['id']; hitokoto = json['hitokoto']; type = json['type']; from = json['from']; fromWho = json['from_who']; creator = json['creator']; creatorUid = json['creator_uid']; reviewer = json['reviewer']; uuid = json['uuid']; createdAt = json['created_at']; } Map toJson() { final Map data = new Map (); data['id'] = this.id; data['hitokoto'] = this.hitokoto; data['type'] = this.type; data['from'] = this.from; data['from_who'] = this.fromWho; data['creator'] = this.creator; data['creator_uid'] = this.creatorUid; data['reviewer'] = this.reviewer; data['uuid'] = this.uuid; data['created_at'] = this.createdAt; return data; }}
OneSentence.fromJson
可以将Map转化为Bean对象。oneSentence.toJson
可以将Bean类转化Json。使用
OneSentence.fromJson
可以将Map转化为Bean对象,那么怎么将Json字符串转化为Map
呢?
import 'dart:convert';Map userMap = json.decode(jsonString);
因此,Json字符串需要先用dart:convert
库下的json.decode
将字符串转化为Map
,之后使用Bean.fromJson(Map)
将Json转化为Bean对象;至于Bean转Json则直接调用Bean
类的toJson方法即可。
转载地址:http://qqzrj.baihongyu.com/