当前位置: 代码迷 >> 综合 >> Dart(*)JSON序列化
  详细解决方案

Dart(*)JSON序列化

热度:50   发布时间:2024-01-11 20:16:05.0

1、配置

1.1、在命令终端进去项目主目录下执行编译监听命令:

flutter packages pub run build_runner watch


1.2、在pubspec.yaml配置文件中添加json_serializable库的依赖:

dev_dependencies:1.0.0json_serializable: ^2.0.0

1.3、新建实体类,写好类与字段以及构造函数:

class Date {String iso;String __type = "Date";Date();
}

1.4、导入JSON依赖:

import 'package:json_annotation/json_annotation.dart';

1.5、配置类以及序列化、反序列化的方法:

//此处与类名一致,由指令自动生成代码
part 'date.g.dart';@JsonSerializable()
class Date {String iso;String __type = "Date";Date();//此处与类名一致,由指令自动生成代码factory Date.fromJson(Map<String, dynamic> json) => _$DateFromJson(json);//此处与类名一致,由指令自动生成代码Map<String, dynamic> toJson() => _$DateToJson(this);
}

1.6、自动生成序列化、反序列化方法类:

// GENERATED CODE - DO NOT MODIFY BY HANDpart of 'date.dart';// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************Date _$DateFromJson(Map<String, dynamic> json) {return Date()..iso = json['iso'] as String;
}Map<String, dynamic> _$DateToJson(Date instance) =><String, dynamic>{'iso': instance.iso};

但是因为__type是以下划线开头,在Dart中以下划线开头的字段不能被其他类可见,所以导致对于__type的操作被过滤了。

1.7、对特殊字段进行注解

import 'package:json_annotation/json_annotation.dart';//此处与类名一致,由指令自动生成代码
part 'date.g.dart';@JsonSerializable()
class Date {String iso;@JsonKey(name: "__type")String type = "Date";Date();//此处与类名一致,由指令自动生成代码factory Date.fromJson(Map<String, dynamic> json) => _$DateFromJson(json);//此处与类名一致,由指令自动生成代码Map<String, dynamic> toJson() => _$DateToJson(this);
}

将__type字段名改为type,并注解名字为__type,生成正确的序列化、反序列化的方法类:

// GENERATED CODE - DO NOT MODIFY BY HANDpart of 'date.dart';// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************Date _$DateFromJson(Map<String, dynamic> json) {return Date()..iso = json['iso'] as String..type = json['__type'] as String;
}Map<String, dynamic> _$DateToJson(Date instance) =><String, dynamic>{'iso': instance.iso, '__type': instance.type};

2、使用

2.1导入依赖

import 'package:data/study/date.dart';

2.2、序列化和反序列化

void testJson(){Map<String,dynamic> mapOri = Map();mapOri["iso"] = "iso value";mapOri["__type"] = "type value";Date date = Date.fromJson(mapOri);print(date.iso);print(date.type);Map<String,dynamic> mapDst = date.toJson();print(mapDst["iso"]);print(mapDst["__type"]);
}