Skip to content

Instantly share code, notes, and snippets.

@take4blue
Created May 5, 2022 01:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save take4blue/daa2f09501b0d3bea11b0e866bdfe870 to your computer and use it in GitHub Desktop.
Save take4blue/daa2f09501b0d3bea11b0e866bdfe870 to your computer and use it in GitHub Desktop.
json_serializable:A sample that serializes and deserializes inherited classes.
import 'dart:convert';
import 'package:json_annotation/json_annotation.dart';
part 'dart_sample1.g.dart';
@JsonSerializable()
class ClassA {
static const classType = "type";
final String title;
final int count;
ClassA({required this.title, required this.count});
void output() {
print("title = $title, count = $count");
}
static Map<String, ClassA Function(Map<String, dynamic>)> factorymap = {};
factory ClassA.fromJson(Map<String, dynamic> json) {
if (!json.containsKey(classType)) {
return _$ClassAFromJson(json);
} else {
return factorymap[json[classType] as String]!(json);
}
}
Map<String, dynamic> toJson() => _$ClassAToJson(this);
}
@JsonSerializable()
class ClassB extends ClassA {
static const className = "classb";
final double value;
@override
void output() {
print("title = $title, count = $count value = $value");
}
ClassB({required title, required count, required this.value})
: super(title: title, count: count);
factory ClassB.fromJson(Map<String, dynamic> json) => _$ClassBFromJson(json);
@override
Map<String, dynamic> toJson() {
final result = _$ClassBToJson(this);
result[ClassA.classType] = className;
return result;
}
static void register() {
ClassA.factorymap[className] = ClassB.fromJson;
}
}
@JsonSerializable()
class ListClass {
final List<ClassA> list;
ListClass({required this.list});
factory ListClass.create() => ListClass(list: <ClassA>[]);
factory ListClass.fromJson(Map<String, dynamic> json) =>
_$ListClassFromJson(json);
Map<String, dynamic> toJson() => _$ListClassToJson(this);
void output() {
for (final i in list) {
i.output();
}
}
}
/// JSONのシリアライズ・デシリアライズ本体。
void jsonProcess() {
ClassB.register();
final list = ListClass.create();
list.list.add(ClassA(title: "hoge", count: 5));
list.list.add(ClassA(title: "hage", count: 5));
list.list.add(ClassB(title: "fuga", count: 3, value: 2.0));
print("list");
list.output();
var jstr = json.encode(list.toJson());
print(jstr);
final result = ListClass.fromJson(json.decode(jstr));
print("result");
result.output();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment