Serialization and deserialization of JSON is a common operation in daily development. If we parse JSON data manually, it is very troublesome. It saves a lot of work if you can do it automatically. Here are five common conversions:

Manually serialize JSON

Define those attributes manually, implement fromJson and toJson, and call them when parsing

ProductItemModel.fromJson(result.data)
Copy the code
class ProductItemModel { String? sId; //String? Represents the nullable type String? title; ProductItemModel( {this.sId, this.title, }); ProductItemModel.fromJson(Map<String, dynamic> json) { sId = json['_id']; title = json['title']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['_id'] = this.sId; data['title'] = this.title; return data; }}Copy the code

Tools to implement

Automatic conversion tool in iOS: juejin.cn/post/702689…

The conversion tool found in Flutter, app.quickType. IO, is also relatively useful.

This will enable transformation. Because Flutter disables runtime reflection, mature libraries such as MJExtension and YYModel are not fully parsed. Here we introduce a relatively mature library jSON_serializable that can be transformed.

Json_serializable implementation

Add dependencies to the project’s pubspec.yaml file:

Json_serializable: ^6.1.3 build_runner: ^2.1.7 jSON_annotation: ^4.4.0Copy the code

Then execute pub get. To use transformation, first of all need to use tools to generate a model class, tool address: caijinglong. Making. IO/json2dart/I…

Create a model class in your project and copy the tool transformation code into this model class

import 'package:json_annotation/json_annotation.dart';

part 'person.g.dart';


List<person> getpersonList(List<dynamic> list){
  List<person> result = [];
  list.forEach((item){
    result.add(person.fromJson(item));
  });
  return result;
}
@JsonSerializable()
class person extends Object with _$personSerializerMixin{

  @JsonKey(name: 'name')
  String name;

  @JsonKey(name: 'age')
  String age;

  @JsonKey(name: 'tele')
  String tele;

  person(this.name,this.age,this.tele,);

  factory person.fromJson(Map<String, dynamic> srcJson) => _$personFromJson(srcJson);

}
Copy the code

Then execute the flutter Packages pub run build_runner watch on the terminal to generate the person.g.art file in the project, which contains the transformed code.

The person.g.art file can also be generated by executing the flutter packages pub run build_runner build.

Note that when using the above tool, the data in the first map in the list will be parsed. If there are too many other map fields in the array, there will be fields missing. This should be checked carefully. It is not very convenient to use as a whole. It is better to use a tool to generate it directly: app.quickType. IO.

Plug-in JsonToDart implementation

Install the JsonToDart plugin in Android Studio, open Preferences (Mac) or Setting (Window), select Plugins, and search for JsonToDart

Click Install to Install, and then restart. Select the directory, right click, and select New->Json to Dart, or use the shortcut key

Windows: ALT + Shift + D Mac: Option + Shift + DCopy the code

After selecting Json To Dart, a page is displayed To enter the Json data To be converted

Click Finish and the corresponding model file will be generated.

Plugin FlutterJsonBeanFactory implementation

Use CMD + to open preferences and then search for FlutterJsonBeanFactory in Plugins

Click Install to Install, and then restart. At this point select the directory, right-click, and select New->JsonToDartBeanAction

Type Class Name, copy the JSON data to be parsed into the JSON Text here, and then hit Make to generate the dart file for the model.

Here you can see that the data requested over the network has indeed been successfully converted.

Note: If we enter a Class Name that does not conform to the Dart syntax, the Name is automatically changed to a_b_C_entity. Dart. The class name generated automatically is entity, which we can actually change.

Typically, the plugin will install the name of the key generated property in the JSON data. If you want to customize it, change the value of the property in the generated Dart file and click here to change it all.

The two plug-ins used above are Android Studio, after conversion or self-check, in case of conversion errors.

conclusion

  • Serializing JSON manually: Cumbersome and inefficient.
  • Json_serializable: High efficiency, still somewhat troublesome.
  • Tool site: high efficiency, more functions optional.
  • Plug-in: high efficiency, the most convenient to use.