Whether there are Gson, FastJson libraries in Flutter

In Android native development, we have third-party libraries like Gson and FastJson to help us turn JSON into entity classes. However, there may not be any third-party libraries for us to use with Flutter, for reasons that you can see. Basically, these third-party libraries use reflection to turn JSON into entity classes, and Flutter prohibits reflection. So how do we translate JSON to entity classes in Flutter without a JSON parsing library?

Manually serialize the JSON using dart: Convert

The basic JSON serialization in Flutter is very simple. There is a built-in DART: Convert library with Flutter that contains a simple JSON encoder and JSON decoder.

  1. Here is a simple user model
{
  "name": "John Smith",
  "email": "[email protected]"
}
Copy the code
  1. Serialize JSON to map

Using the jsonDecode () method in the Dart: Convert library, we can turn json into a Map by taking a JSON string as its argument

Map<String, dynamic> user = jsonDecode(jsonString); print('Howdy, ${user['name']}! '); print('We sent the verification link to ${user['email']}.');Copy the code

The problem is that jsonDecode () returns a Map<String,dynamic>, and dynamic is the dynamic type, meaning that you don’t know the types of these values until run time. Using this approach, you lose most of the features of statically typed languages: type safety, auto-complete capabilities, and most importantly, compile-time exceptions. Your code will immediately become more error-prone. For example, every time you access a name or email field, you can quickly type a typo. JSON exists in the map structure and is therefore a typo unknown to the compiler.

  1. Serialize the JSON in the model class

We can solve the previous problem with an introduced model class, User. In User we define:

  • A user.fromjson () constructor that constructs a new User instance from the Map structure object
  • A method for toJson() to transform a User instance into a Map.

user.dart

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

Now that the decoded logic has been moved inside the User of the model, you can easily decode a User instance with this new approach

Map<String, dynamic> userMap = jsonDecode(jsonString); var user = User.fromJson(userMap); print('Howdy, ${user.name}! '); print('We sent the verification link to ${user.email}.');Copy the code

To encrypt the user, you can upload the User object into the jsonEncode() function and convert the user instance into a JSON string without calling the toJson() method

String userJson = jsonDecode(user);

Copy the code

In this way, we can do simple JSON serialization, but the problem becomes very complex. Usually we only need to do one step of JSON parsing in Java. In Dart we need to break it down into two steps. First we need to call jsonDecode in Dart to turn it into a map, and then we need to define the related methods in the model.

  • You must first convert the JSON string to a Map using the jsonDecode method
  • The fromJson and toJson functions must be defined in the model class, which can be very difficult to write with complex data
  • With json structures of nested types, things get even more complicated. Greatly affecting our development efficiency

So since JSON serialization is so complex to use, is there a better way to do it? See below!

Use third-party plug-ins for JSON parsing

  1. Installing a plug-in

  1. The use of plug-in

Right-click package ->New->JsonToDartBeanAction to display the following interface

Enter the class name and json string, and we can easily get the model class we want.

Such as:

import 'package:kooielts/generated/json/base/json_convert_content.dart';

class DogEntity with JsonConvert<DogEntity> {
	String code;
	String message;
	List<DogObj> obj;
}

class DogObj with JsonConvert<DogObj> {
	String appName;
	String nickName;
	String appId;
	String headImage;
	int userId;
}
Copy the code

The JsonConvert base class in this class helps us convert from map to model (fromJson method) and from model to map(toJson method). With the dart native library, Dart: Convert and FlutterJsonBeanFactory plugin, you’re ready for json parsing.

Note: The JSON parsing plug-in supports both empty and non-empty security models. If you want to use an empty security model, your dart version must be at least larger than 2.12.0, otherwise choose to generate beans in a non-empty security way.

Environment: the SDK: "> = 2.12.0 < 3.0.0"Copy the code