json_serializable:A sample that serializes and deserializes inherited classes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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