一种适用于最小规模的解决方案。
pupspec.yaml:
name: playground
description: A simple command-line application.
environment:
sdk: '>=2.8.1 <3.0.0'
dependencies:
json_annotation: ^3.0.1
dev_dependencies:
build_runner: ^1.10.0
json_serializable: ^3.3.0
pedantic: ^1.9.0
操场飞镖:
import 'package:json_annotation/json_annotation.dart';
part 'playground.g.dart';
enum Letter{ A, B, C}
@JsonSerializable()
class example{
example(){}
@JsonKey(fromJson: parseMap, toJson: toStringMap)
Map<String, Letter> letters = {
'A': Letter.A,
'B':Letter.B
};
factory example.fromJson(Map<String, dynamic> json) => _$exampleFromJson(json);
Map<String, dynamic> toJson() => _$exampleToJson(this);
static Map<String, Letter> parseMap(Map<String,String> m){
if(m==null){
return {
'C': Letter.C
};
}
Map<String, Letter> result ={};
for(String key in m.keys){
result[key]=Letter.values.firstWhere((e) => e.toString() == m[key]);
}
return result;
}
static Map<String, String> toStringMap(Map<String,Letter> m){
if(m==null){
return {
'C': 'C'
};
}
Map<String, String> result ={};
for(String key in m.keys){
result[key]=m[key].toString();
}
return result;
}
}
void main(List<String> arguments) {
var ex = example.fromJson({});
print(ex.letters.values);
var ex2 = new example();
var m =ex2.toJson();
print(m);
var ex3 = new example();
ex3.letters=null;
var m2 =ex3.toJson();
print(m2);
}
跑:
pub run build_runner build
dart .\bin\playground.dart
输出:
(字母.C)
{字母:{A:字母.A,B:字母.B}}
{字母:{C:C}}