Preface
Implement json string serialization and deserialization using the json_annotation framework
Framework official address:json_serializable
1. Introduce dependencies: add in pubspec.yaml
dependencies:
json_annotation: ^4.8.1
dev_dependencies:
build_runner: ^2.3.3
json_serializable: ^6.6.0
2. Usage process
data source:
{
"id": 1,
"name": "John",
"email": "[email protected]",
"phone_numbers": [
{
"type": "home",
"number": "1234567890"
},
{
"type": "work",
"number": "0987654321"
}
]
}
Create data model:
// 引入依赖
import 'package:json_annotation/json_annotation.dart';
// 指定此类的代码生成文件(格式:part '类名.g.dart';)
part 'Person.g.dart';
// 添加序列化标注
@JsonSerializable()
class Person {
int id;
String name;
String email;
// 使用别名
@JsonKey(name: "phone_numbers")
List<PhoneNumber> phoneNumbers;
Person(this.id, this.name, this.email, this.phoneNumbers);
// 添加反序列化方法(格式:factory 类名.fromJson(Map<String, dynamic> json) => _$类名FromJson(json);)
factory Person.fromJson(Map<String,dynamic> json) => _$PersonFromJson(json);
// 添加序列化方法(格式:Map<String, dynamic> toJson() => _$类名ToJson(this);)
Map<String,dynamic> toJson() => _$PersonToJson(this);
}
@JsonSerializable()
class PhoneNumber {
String type;
String number;
PhoneNumber(this.type, this.number);
factory PhoneNumber.fromJson(Map<String,dynamic> json) => _$PhoneNumberFromJson(json);
Map<String,dynamic> toJson() => _$PhoneNumberToJson(this);
}
Use the command to generate the corresponding .g.dart content
Use the following command in the Terminal of android studio:
flutter pub run build_runner build
Command generation process:
PS D:\AndroidStudioProjects\github_client_app> flutter pub run build_runner build
Deprecated. Use `dart run` instead.
Building package executable... (5.9s)
Built build_runner:build_runner.
[INFO] Generating build script completed, took 252ms
[INFO] Reading cached asset graph completed, took 73ms
[INFO] Checking for updates since last build completed, took 685ms
[INFO] Running build completed, took 19.0s
[INFO] Caching finalized dependency graph completed, took 87ms
[INFO] Succeeded after 19.1s with 602 outputs (606 actions)
PS D:\AndroidStudioProjects\github_client_app> flutter pub run build_runner build
Deprecated. Use `dart run` instead.
[INFO] Generating build script completed, took 252ms
[INFO] Reading cached asset graph completed, took 193ms
[INFO] Checking for updates since last build completed, took 683ms
[INFO] Running build completed, took 10.1s
[INFO] Caching finalized dependency graph completed, took 86ms
[INFO] Succeeded after 10.2s with 189 outputs (193 actions)
View Person.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'Person.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Person _$PersonFromJson(Map<String, dynamic> json) => Person(
json['id'] as int,
json['name'] as String,
json['email'] as String,
(json['phone_numbers'] as List<dynamic>)
.map((e) => PhoneNumber.fromJson(e as Map<String, dynamic>))
.toList(),
);
Map<String, dynamic> _$PersonToJson(Person instance) => <String, dynamic>{
'id': instance.id,
'name': instance.name,
'email': instance.email,
'phone_numbers': instance.phoneNumbers,
};
PhoneNumber _$PhoneNumberFromJson(Map<String, dynamic> json) => PhoneNumber(
json['type'] as String,
json['number'] as String,
);
Map<String, dynamic> _$PhoneNumberToJson(PhoneNumber instance) =>
<String, dynamic>{
'type': instance.type,
'number': instance.number,
};
Usage example:
void jsonTest() {
final json = '''
{
"id": 1,
"name": "John",
"email": "[email protected]",
"phone_numbers": [
{
"type": "home",
"number": "1234567890"
},
{
"type": "work",
"number": "0987654321"
}
]
}
''';
final person = Person.fromJson(jsonDecode(json));
print("steve:${person.name}");
final jsonEncoded = jsonEncode(person.toJson());
print("steve:$jsonEncoded");
}
Printed log:
I/flutter ( 1781): steve:John
I/flutter ( 1781): steve:{"id":1,"name":"John","email":"[email protected]","phone_numbers":[{"type":"home","number":"1234567890"},{"type":"work","number":"0987654321"}]}
Replenish:
jsonKey
nullable
: The default istrue
, which means the field can benull
.defaultValue
: If the sourceJSON
does not contain thekey
or the of thekey
For, provide a default value.value
null
name
: alias, if it isnull
, it defaults to the field name.required
: The default isfalse
. If it is true, it will check whetherJSON
contains thekey
. If not, it will throw Exception (key
is also valid fornull
).
Generate .g.dart file
Build once
flutter packages pub run build_runner build
Delete and rebuild
flutter packages pub run build_runner build --delete-conflicting-outputs
Automatically created for subsequent data models created
flutter packages pub run build_runner watch