使用过Gson等json库的开发者应该知道,这种json解析库使用起来相当方便,你只需创建好实体类,用一两行代码就能实现把java对象转化成json字符串,以及把json字符串转化成java对象。
在flutter里也有类似的库吗?
官方的回答是:并没有。链接:https://flutter.io/json/#is-there-a-gsonjacksonmoshi-equivalent-in-flutter
解决办法:
方法一
手写。
参考: https://flutter.io/cookbook/networking/fetch-data/
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({this.userId, this.id, this.title, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
使用方法:
Future<Post> fetchPost() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/posts/1');
if (response.statusCode == 200) {
// If server returns an OK response, parse the JSON
return Post.fromJson(json.decode(response.body));
} else {
// If that response was not OK, throw an error.
throw Exception('Failed to load post');
}
}
json.decode方法源自dart:convert,它可以将json字符串转化成Map<String, dynamic>的类型。
缺点:如果接口里的属性比较多,写起来相当繁琐,而且容易出错。
方法二
使用https://github.com/debuggerx01/JSONFormat4Flutter 这样的第三方json2bean的代码生成工具。
缺点:生成的类里的部分方法可能不符合你的需求,需要手动做一些调整。
方法三:
使用json_annotation + json_serializable。
首先给项目添加依赖:
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
fluttertoast: ^2.0.3
json_annotation: ^0.2.3
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^0.8.0
json_serializable: ^0.5.0
我个人的经验是:添加依赖后,不要手动的去点界面上的“packages get”,容易卡住,控制台只显示一句“Running "flutter packages get" in xxxx”,过了很久都没有任何反应。
建议到Terminal窗口手动输入“flutter packages get”去运行。这样的好处是可以随时用Ctrl+C取消命令。
如果下载不下来依赖库,试试给Android Studio添加一下http代理。同时检查一下代理是否能连得上官网“https://pub.dartlang.org”。
创建实体类
假设json结构如下:
{
"name":"book1",
"author":{"name":"Jack"},
"publishDate":"2018-10-10",
"publisher":"xxx company"
}
创建实体类:
Book.dart:
import 'package:flutter_app2/json/Author.dart';
import 'package:json_annotation/json_annotation.dart';
part 'Book.g.dart';
@JsonSerializable()
class Book extends Object with _$BookSerializerMixin {
String name;
Author author;
String publishDate;
String publisher;
Book(this.name, this.author, this.publishDate, this.publisher);
@override
String toString() {
return 'Book{name: $name, author: $author, publishDate: $publishDate, publisher: $publisher}';
}
factory Book.fromJson(Map<String, dynamic> json) => _$BookFromJson(json);
}
Author.dart
import 'package:json_annotation/json_annotation.dart';
part 'Author.g.dart';
@JsonSerializable()
class Author extends Object with _$AuthorSerializerMixin {
String name;
Author(this.name);
@override
String toString() {
return 'Author{name: $name}';
}
factory Author.fromJson(Map<String, dynamic> json) => _$AuthorFromJson(json);
}
自动生成json解析代码
在Terminal窗口运行
flutter packages pub run build_runner build
就能看到自动生成了Author.g.dart和Book.g.dart两个文件。
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'Author.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Author _$AuthorFromJson(Map<String, dynamic> json) =>
new Author(json['name'] as String);
abstract class _$AuthorSerializerMixin {
String get name;
Map<String, dynamic> toJson() => <String, dynamic>{'name': name};
}
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'Book.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Book _$BookFromJson(Map<String, dynamic> json) => new Book(
json['name'] as String,
json['author'] == null
? null
: new Author.fromJson(json['author'] as Map<String, dynamic>),
json['publishDate'] as String,
json['publisher'] as String);
abstract class _$BookSerializerMixin {
String get name;
Author get author;
String get publishDate;
String get publisher;
Map<String, dynamic> toJson() => <String, dynamic>{
'name': name,
'author': author,
'publishDate': publishDate,
'publisher': publisher
};
}
使用
var book = new Book("book1", new Author("Jack"), "2018-10-10", "xxx company");
print("book="+book.toString());
String jsonStr= json.encode(book);
print("json="+jsonStr);
var bookAfter= Book.fromJson(json.decode(jsonStr));
print("from json="+bookAfter.toString());
注意要使用json.encode和json.decode,需要引入:
import 'dart:convert';
打印结果:
book=Book{name: book1, author: Author{name: Jack}, publishDate: 2018-10-10, publisher: xxx company}
json={"name":"book1","author":{"name":"Jack"},"publishDate":"2018-10-10","publisher":"xxx company"}
from json=Book{name: book1, author: Author{name: Jack}, publishDate: 2018-10-10, publisher: xxx company}
总结
这种方式是官方目前推荐的方案。
另外,执行
flutter packages pub run build_runner watch
可以实现文件监听,自动地为你后续创建的实体类生成对应的解析代码。
我尝试了一下这个命令,以下是操作步骤:
新建一个Animal.dart
添加 import 'package:json_annotation/json_annotation.dart';
添加 part 'Animal.g.dart';
添加继承关系 extends Object with _$AnimalSerializerMixin
添加各种属性
添加一行代码:
factory Animal.fromJson(Map<String, dynamic> json) => _$AnimalFromJson(json);
发现Terminal控制台提示"Unsupported operation: The class `Animal` has no default constructor."
手动创建一个构造函数
发现 Animal.g.dart 已经自动生成成功。
效果还算不错。