Skip to content

Instantly share code, notes, and snippets.

Created May 5, 2022 01:43
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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';
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);
class ClassB extends ClassA {
static const className = "classb";
final double value;
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);
Map<String, dynamic> toJson() {
final result = _$ClassBToJson(this);
result[ClassA.classType] = className;
return result;
static void register() {
ClassA.factorymap[className] = ClassB.fromJson;
class ListClass {
final List<ClassA> list;
ListClass({required this.list});
factory ListClass.create() => ListClass(list: <ClassA>[]);
factory ListClass.fromJson(Map<String, dynamic> json) =>
Map<String, dynamic> toJson() => _$ListClassToJson(this);
void output() {
for (final i in list) {
/// JSONのシリアライズ・デシリアライズ本体。
void jsonProcess() {
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));
var jstr = json.encode(list.toJson());
final result = ListClass.fromJson(json.decode(jstr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment