Double the efficiency! Large-scale Flutter project quickly realizes JSON to Model actual combat

I. Introduction

In native application development, we usually use YYModel, SwiftyJSON, , GSONand other libraries to implement JSONparsing, and use JSONConverter and other similar tools to automatically convert JSON to models, which greatly improves work efficiency. But in Flutter development, there is no similar parsing library for us to use, because such a library needs to use runtime reflection, which is disabled in Flutter. Runtime reflection interferes with Dart's tree shaking. Using _tree shaking_it, you can "strip" unused code in releases, which can significantly optimize the size of your application. Since reflection is applied to all code by default, it _tree shaking_ can be difficult to work, because it is difficult to know which code is not used when reflection is enabled, so redundant code is difficult to strip, so Dart's reflection feature is disabled in Flutter, and because of In this way, the function of dynamically converting Model cannot be realized.

2. json_serializable

Although runtime reflection cannot be used in Flutter, the official provides a similar easy-to-use API, which is implemented based on the code generation library, json_serializable package , which is an automated source code generator that can generate JSON serialization templates, due to the sequence The code does not need to be handwritten and maintained, which minimizes the risk of JSON serialization exceptions at runtime. The usage methods are as follows:

1. Add in the projectjson_serializable

To be included json_serializablein our project, one general and two development dependencies are required. In short, development dependencies are dependencies that are not included in our application source code. Follow this link to view the latest versions of these required dependencies.

json_serializable.png

Run in your project root folder flutter packages get (or hit "Packages Get" in the editor) to use these new dependencies in your project.

2. Create the model class as json_serializable

Let's see how to convert our User class to a json_serializable. For simplicity, we use the simplified JSON model from the previous example.

user.dart

import 'package:json_annotation/json_annotation.dart';

// user.g.dart 将在我们运行生成命令后自动生成
part 'user.g.dart';

///这个标注是告诉生成器,这个类是需要生成Model类的
@JsonSerializable()
class User {
  String name;
  String email;

  User(this.name, this.email);

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}
复制代码

With this setting, the source generator will generate JSON code for serializing the name and email fields.

It is also easy to customize the naming strategy if needed. For example, if we are using an API that returns objects with _snake_case_, but we want to use _lowerCamelCase_ in our model, then we can use the @JsonKey annotation:

@JsonKey(name: 'registration_date_millis')
final int registrationDateMillis;
复制代码

3. Run the code generator

  • one-time generation

By running from our project root flutter packages pub run build_runner build, we can generate JSON serialization code for our Model when needed. This triggers a one-time build that goes through our source files, picks out the relevant ones and generates the necessary serialization code for them.

  • Continuous generation

While this is very convenient, it would be better if we didn't need to manually run the build command every time we make a change in the model class. Using _watcher_ can make the process of generating our source code more convenient. It monitors changes to files in our project and automatically builds the necessary files when needed. We can flutter packages pub run build_runner watchstart _watcher_ by running in the project root directory. Just start the watcher once and let it run in the background, it's safe

4. Use the json_serializablemodel

To json_serializabledeserialize a JSON string by way, we don't need to make any changes to the previous code.

Map userMap = JSON.decode(json);
var user = new User.fromJson(userMap);
复制代码

The same goes for serialization. Calling the API is the same as before.

String json = JSON.encode(user);
复制代码

With json_serializablethat, we just need to write Userthe class file. The source code generator creates a user.g.dartfile called , which has all the necessary serialization logic. Now, we don't have to write automated tests to make sure serialization works - this library will make sure serialization works.

3. JSONConverter

As written above, even if you use it json_serializable, you still need to manually write the model class files and write the corresponding model attributes one by one. There may be hundreds of APIs in a project in production work. If all handwriting is still a waste of time, here we will You can use JSONConverter , which can automatically generate model files according to the JSON returned from the background. With cooperation json_serializable, it is very convenient to realize interface docking, and model files can be generated with one click, which greatly saves the programmer's physical strength.

Flutter-JSONConverter.pngIn JSONConverteraddition to supporting Flutter, it also supports other languages ​​and third-party libraries, and the functions may be very rich.

JSONConverter.png

4. Summary

In the production project, it is recommended to use json_serializable+ JSONConverter to complete the JSON data parsing work returned by the server, and the efficiency is doubled! !

Guess you like

Origin juejin.im/post/7098890613839364127