Open bingoogolapple opened 5 years ago
import 'package:json_annotation/json_annotation.dart';
part 'json_converter_example.g.dart';
@JsonSerializable()
class GenericCollection<T> {
@JsonKey(name: 'page')
final int page;
@JsonKey(name: 'total_results')
final int totalResults;
@JsonKey(name: 'total_pages')
final int totalPages;
@JsonKey(name: 'results')
@_Converter()
final List<T> results;
GenericCollection({this.page, this.totalResults, this.totalPages, this.results});
factory GenericCollection.fromJson(Map<String, dynamic> json) => _$GenericCollectionFromJson<T>(json);
Map<String, dynamic> toJson() => _$GenericCollectionToJson(this);
}
class _Converter<T> implements JsonConverter<T, Object> {
const _Converter();
@override
T fromJson(Object json) {
if (json is Map<String, dynamic> && json.containsKey('name') && json.containsKey('size')) {
return CustomResult.fromJson(json) as T;
}
// 只有在 json 是 JSON 基本类型时才有效:num,String,bool,null 等,强制类型转换为 T
return json as T;
}
@override
Object toJson(T object) {
// 只有在 object 是 JSON 基本类型时才有效:num,String,bool,null 等,或有 toJson 方法
return object;
}
}
@JsonSerializable()
class CustomResult {
final String name;
final int size;
CustomResult(this.name, this.size);
factory CustomResult.fromJson(Map<String, dynamic> json) => _$CustomResultFromJson(json);
Map<String, dynamic> toJson() => _$CustomResultToJson(this);
@override
bool operator ==(Object other) => other is CustomResult && other.name == name && other.size == size;
@override
int get hashCode => name.hashCode * 31 ^ size.hashCode;
}
import 'dart:convert';
jsonDecode(Json字符串)
jsonEncode(对象)
String _encode(Object object) => const JsonEncoder.withIndent(' ').convert(object);
接入 json_serializable