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.根據(jù)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是我自定義的實體類憋槐,這個類同樣需要執(zhí)行上述的“一般步驟“*/
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
,這個命令可以實現(xiàn)文件監(jiān)聽,自動地為你后續(xù)創(chuàng)建的實體類生成對應的.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":"地產小區(qū)"}}';
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, "地產小區(qū)"));
String snjsonStr = json.encode(snp);
print("new sn-json=" + snjsonStr);
var snpAfter2 = BaiduSNComputePosition.fromJson(json.decode(snjsonString));
print("反序列化toString=" + snpAfter2.toString());
}