serialization

Manually serialize JSON using DART :convert

Flutter has a built-in Dart: Convert library with Json encoders and decoders.

class User {
  final String name;
  final String email;

  User(this.name, this.email);

  User.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        email = json['email'];

  Map<String, dynamic> toJson() =>
    {
      'name': name,
      'email': email,
    };
}
Copy the code

Deserialization and serialization

// deserialize Map userMap = json.decode (JSON); var user = new User.fromJson(userMap); print('Howdy, ${user.name}! '); print('We sent the verification link to ${user.email}.'); // serialize String json = json.encode (user);Copy the code

Serialize JSON using a code generation library

Yaml relies on jSON_serialIZABLE in pubSpec.yaml and then pulls the library flutter Packages GET

Json_annotations: ^2.0.0 dev_dependencies: # Your other dev_dependencies here build_runner: ^1.0.0 jSON_serialIZABLE: ^2.0.0Copy the code
import 'package:json_annotation/json_annotation.dart'; part 'user.g.dart'; (After writing the part reference, running the command automatically generates the corresponding file.) @jSonSerialIZABLE () class User{User(this.name, this.email); String name; String email; Factory user.fromjson (Map<String, dynamic> json) => _$UserFromJson(json); Map<String, dynamic> toJson() => _$UserToJson(this); }Copy the code

There are two ways to generate it

By running flutter Packages pub Run build_runner build in our project root directory, we can generate JSON serialization code for our model as needed. This triggers a one-time build, which picks the relevant ones through our source files and generates the necessary serialization code for them. Generator Cannot target libraries That have not been migrated to null-safety. Wrong version blog.csdn.net/a939006659/… While this is very convenient, it would be nice if we didn’t have to run the build command manually every time we made a change in the Model class. Continuous generation using _watcher_ makes our source code generation process much easier. It monitors changes to the files in our project and automatically builds the necessary files as needed. We can start _watcher_ by running the flutter Packages pub run build_runner watch under the project root directory. It’s safe to just start the observer once, and then let it run in the background.

Deserialization and serial numbers

// deserialize Map userMap = json.decode (JSON); var user = new User.fromJson(userMap); // serialize String json = json.encode (user);Copy the code

Nested model parsing

import 'package:json_annotation/json_annotation.dart';
part 'NestModel.g.dart';

class NestModel{

  final name;
  final email;
  final List<NestModel> childrens;
  final NestModel nest;

  NestModel(this.name, this.email, this.childrens,this.nest);

  factory NestModel.fromJson(Map<String, dynamic> json) => _$NestModelFromJson(json);
  Map<String, dynamic> toJson() => _$NestModelToJson(this);
}
Copy the code

This time the automatic serialization of the library benefits reflected, do not have to write multiple attributes one by one assignment, nested deserialization in the parameter is difficult to write, here out of the automatic code

NestModel _$NestModelFromJson(Map<String, dynamic> json) { return NestModel( json['name'], json['email'], (json['childrens'] as List) ? .map((e) => e == null ? null : NestModel.fromJson(e as Map<String, dynamic>)) ?.toList(), json['nest'] == null ? null : NestModel.fromJson(json['nest'] as Map<String, dynamic>), ); } Map<String, dynamic> _$NestModelToJson(NestModel instance) => <String, dynamic>{ 'name': instance.name, 'email': instance.email, 'childrens': instance.childrens, 'nest': instance.nest, };Copy the code