json数据格式转换
- 使用json_serializable库
- pubspec.yaml文件中添加依赖
dependencies:
json_annotation: ^4.4.0
dev_dependencies:
build_runner: ^2.1.4
json_serializable: ^6.7.1
- 使用@JsonSerializable注解标记类
import 'package:json_annotation/json_annotation.dart';
import '../dio/HttpState.dart';
part 'BaseResponse.g.dart';
@JsonSerializable(genericArgumentFactories: true)
class BaseResponse<T> {
int status = 0;
T? data;
String? title;
BaseResponse({
required this.data,
required this.status,
required this.title,
});
bool isSuccess() {
return status == HttpState.SUCCESS;
}
String getMessageAndCodeWithEmpty() {
if (title == null) {
return "";
} else {
return "${title!}:$status";
}
}
factory BaseResponse.fromJson(
Map<String, dynamic> json,
T Function(dynamic json) fromJsonT,
) =>
_$BaseResponseFromJson<T>(json, fromJsonT);
Map<String, dynamic> toJson(Object? Function(T value) toJsonT) =>
_$BaseResponseToJson<T>(this, toJsonT);
}
- 运行以下命令生成序列化文件
flutter pub run build_runner build
- 导入生成一个名为xx.g.dart的文件
- 泛型处理
part 'UserInfo.g.dart';
@JsonSerializable(explicitToJson: true)
class UserInfo {
String? name;
int age = 0;
String? email;
UserInfo({
required this.name,
required this.age,
required this.email,
});
factory UserInfo.fromJson(Map<String, dynamic> json) =>
_$UserInfoFromJson(json);
Map<String, dynamic> toJson() => _$UserInfoToJson(this);
}
BaseResponse和UserInfo中的factory直接调用xx.g.dart文件
测试
void _checkJson(){
String jsonString = '{"status":200,"data":{"name":"张三","age":18}}';
Map<String,dynamic> jsonData = json.decode(jsonString);
BaseResponse<UserInfo>? response = BaseResponse<UserInfo>.fromJson(jsonData, (json) => UserInfo.fromJson(json));
Log.e("用户名称:${response.data?.name}");
}
网友评论