1.引入json_annotation依赖
pubspec.yaml
dependencies:
# Your other regular dependencies here
json_annotation: ^2.0.0
dev_dependencies:
# Your other dev_dependencies here
build_runner: ^1.0.0
json_serializable: ^2.0.0
2.根据json字符串的结构和字段构造实体类(model),注意字段类型
一般步骤为:
- 新建类和属性(字段)以及带参构造方法,注意属性类型。
- 引入
json_annotation
,即插入import 'package:json_annotation/json_annotation.dart';
。 - 指定此类的生成代码,
part '类名.g.dart';
。 - 添加序列化标注,
@JsonSerializable()
,注意括号。 - 添加反序列化和序列化方法
fromJson
和toJson
,即factory 类名.fromJson(Map<String, dynamic> json) =>_$类名FromJson(json);
和Map<String, dynamic> toJson() => _$类名ToJson(this);
。
例:BaiduSNComputePosition.dart
//引入json_annotation
import 'package:json_annotation/json_annotation.dart';
import 'package:flutter_app/model/SnResult.dart';
//此类的生成代码,part '类名.g.dart';
part 'BaiduSNComputePosition.g.dart';
//序列化标注
@JsonSerializable()
class BaiduSNComputePosition {
//不加任何JsonKey默认允许空json字段
int status;
/*SnResult是我自定义的实体类,这个类同样需要执行上述的“一般步骤“*/
SnResult result;
//构造方法
BaiduSNComputePosition(this.status, this.result);
//反序列化,factory *.fromJson(Map<String, dynamic> json) =>_$*FromJson(json);
factory BaiduSNComputePosition.fromJson(Map<String, dynamic> json) =>
_$BaiduSNComputePositionFromJson(json);
//序列化,Map<String, dynamic> toJson() => _$*ToJson(this);
Map<String, dynamic> toJson() => _$BaiduSNComputePositionToJson(this);
@override
String toString() {
return '{status: $status, result: $result}';
}
}
3.生成对应的.g.dart文件
忽略报错,使用命令flutter packages pub run build_runner build
进行一次性构建,构建过程中flutter会使用Model类的源文件(包含@JsonSerializable标注的)来生成对应的.g.dart文件。
另外,也可以使用命令flutter packages pub run build_runner watch
,这个命令可以实现文件监听,自动地为你后续创建的实体类生成对应的.g.dart文件。
这里给出上述实体类例子的对应.g.dart文件:BaiduSNComputePosition.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'BaiduSNComputePosition.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
BaiduSNComputePosition _$BaiduSNComputePositionFromJson(
Map<String, dynamic> json) {
return BaiduSNComputePosition(
json['status'] as int,
json['result'] == null
? null
: SnResult.fromJson(json['result'] as Map<String, dynamic>));
}
Map<String, dynamic> _$BaiduSNComputePositionToJson(
BaiduSNComputePosition instance) =>
<String, dynamic>{'status': instance.status, 'result': instance.result};
4.使用
使用json.encode
和json.decode
,需要引入import 'dart:convert';
。
//序列化为json字符串,变量modelObject是实体类对象
String jsonStr = json.encode(modelObject);
//反序列化为实体类,变量jsonString是与实体类完全匹配的json字符串,BaiduWebPosition是实体类名
var modelObj= BaiduWebPosition.fromJson(json.decode(jsonString));
以下是我在单元测试中的例子:
import 'dart:convert';
import 'package:flutter_app/model/Address_detail.dart';
import 'package:flutter_app/model/BWPContent.dart';
import 'package:flutter_app/model/BaiduSNComputePosition.dart';
import 'package:flutter_app/model/BaiduWebPosition.dart';
import 'package:flutter_app/model/Bdpoint.dart';
import 'package:flutter_app/model/SnLocation.dart';
import 'package:flutter_app/model/SnResult.dart';
void main() {
String ipjsonString =
'{"address":"CN|\u5929\u6d25|\u5929\u6d25|None|UNICOM|0|0","content":{"address":"\u5929\u6d25\u5e02","address_detail":{"city":"\u5929\u6d25\u5e02","city_code":332,"district":"","province":"\u5929\u6d25\u5e02","street":"","street_number":""},"point":{"x":"117.21081309","y":"39.14392990"}},"status":0}';
String snjsonString =
'{"status":0,"result":{"location":{"lng":117.04521735270664,"lat":39.11214414784875},"precise":1,"confidence":80,"comprehension":92,"level":"地产小区"}}';
var address = 'CN|\u5929\u6d25|\u5929\u6d25|None|UNICOM|0|0';
var addr = '\u5929\u6d25\u5e02';
var ipp = new BaiduWebPosition(
address,
new BWPContent(
addr,
new Address_detail(
"\u5929\u6d25\u5e02", 332, "", "\u5929\u6d25\u5e02", "", ""),
new Bdpoint("117.21081309", "39.14392990")),
0);
String ipjsonStr = json.encode(ipp);
print("new ip-json=" + ipjsonStr);
var ippAfter = BaiduWebPosition.fromJson(json.decode(ipjsonString));
//我的实体类重写了toString方法哦
print("反序列化toString=" + ippAfter.toString());
var snp = new BaiduSNComputePosition(
0,
new SnResult(new SnLocation(117.04521735270665, 39.11214414784875), 1, 80,
92, "地产小区"));
String snjsonStr = json.encode(snp);
print("new sn-json=" + snjsonStr);
var snpAfter2 = BaiduSNComputePosition.fromJson(json.decode(snjsonString));
print("反序列化toString=" + snpAfter2.toString());
}