当前位置:网站首页>Transfer from fluent JSON to model

Transfer from fluent JSON to model

2020-11-10 13:32:55 June

background


In the development process , The server usually returns JSON Formatted data , about Web Developer (JavaScript、TypeScript) in , You can get it directly JSON Data to do our logic .

JSON Itself originated from JavaScript,JavaScript Parsing JSON There are natural advantages 

But it's like Java、Dart In isointensity typed languages , We need to JSON Data is transferred to model objects to use .

  • In general , We will use some third-party libraries to dynamically transform Model, however Flutter There is no such thing as Java Of GSON/Jackson This kind of JSON Serialization Library .
  • because Flutter Disable runtime reflection in . The official explanation is that runtime reflection interferes with Dart Of Tree Shaking, Use Tree Shaking Can be in Release Remove unused code from the , This can significantly optimize the size of the application .
  • Since reflection is applied to by default Dart Reflection function of , And because of this, it is impossible to realize dynamic transformation Model The function of .

Several schemes of serialization


Flutter There are two official serialization schemes recommended :https://flutterchina.club/json/

  1. Small project manual serialization , This scheme is relatively simple , More suitable for small projects, simple JSON transformation , But the project is huge , Or multiple people working together , It's easy to make mistakes , It's not easy to maintain .

    Flutter There's a built-in dart:convert library 
     Use  dart:convert Manual serialization JSON
  2. Use code generation in medium to large projects , You need to use the following three dependency packages , By means of automatic code generation , Generate models . This solution is easy to maintain , Because the serialization data code no longer needs to be written or maintained manually , You can serialize JSON The risk of data anomalies at runtime is minimized ;

Conversion process


  1. stay pubspec.yaml Add dependency to
json_annotation: ^3.1.0
json_serializable: ^3.5.0
build_runner: ^1.0.0

stay Android Stuido In the implementation of Pub get

  1. New model class (mode/demo_model.dart)
class DemoModel{
    
}
  1. Send the back end request to the web page JSON Data to Model:

    https://czero1995.github.io/json-to-model/: Website transformation supports the transformation of complex objects with infinite levels

    //p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/904e6b0f3048460cbdd7018b06b67ad3~tplv-k3u1fbpfcp-zoom-1.image

  • For example, the following JSON Copy the data to the web page ( On the left ):
{
  "code": 0,
  "data": {
    "avatar": "xxx.png",
    "id": 7,
    "float":0.1,
    "is_deleted": false,
    "nickname": "nickName",
    "openId": null,
    "phone": "13641418383",
    "store_ids": [1,2],
    "updated": "2020-11-05 11:53:10",
    "more":[{"a":1,"b":"b","c":{"c1":0.2,"c2":2}}]
  }
}
  • And then convert to Model data ( On the right )
import 'package:json_annotation/json_annotation.dart';
part 'demo_model_data.g.dart'; 
@JsonSerializable(explicitToJson: true)
class DemoModelModel {
    DemoModelData data;
    DemoModelModel({
      this.data,
      this.code,
      this.message
    });
    factory DemoModelModel.fromJson(Map<String, dynamic> json) => _$DemoModelModelFromJson(json);
    Map<String, dynamic> toJson() => _$DemoModelModelToJson(this);
}

@JsonSerializable(explicitToJson: true)
class DemoModelData {
    String avatar;
    int id;
    double float;
    bool is_deleted;
    String nickname;
    var openId;
    String phone;
    List<int> store_ids; 
    String updated;
    List<MoreData> more; 
    DemoModelData({
        this.avatar, 
        this.id, 
        this.float, 
        this.is_deleted, 
        this.nickname, 
        this.openId, 
        this.phone, 
        this.store_ids, 
        this.updated, 
        this.more, 
    });
  factory DemoModelData.fromJson(Map<String, dynamic> json) => _$DemoModelDataFromJson(json);
  Map<String, dynamic> toJson() => _$DemoModelDataToJson(this);
}

@JsonSerializable(explicitToJson: true) 
class MoreData{ 
    int a;
    String b;
    CData c;
    MoreData({
        this.a, 
        this.b, 
        this.c, 
    });
    factory MoreData.fromJson(Map<String, dynamic> json) => _$MoreDataFromJson(json);
    Map<String, dynamic> toJson() => _$MoreDataToJson(this);
}

@JsonSerializable(explicitToJson: true) 
class CData{ 
    double c1;
    int c2;
    CData({
        this.c1, 
        this.c2, 
    });
    factory CData.fromJson(Map<String, dynamic> json) => _$CDataFromJson(json);
    Map<String, dynamic> toJson() => _$CDataToJson(this);
}

After that, the data will be copied out and then covered demo_model.dart On the file

  1. perform build_runner

Execute the command in the project terminal :

flutter pub run build_runner build

After execution , Will generate demo_model.g.dart file

The whole execution process is as follows

//p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/8bc6bb3edb75410397af822c881b1316~tplv-k3u1fbpfcp-zoom-1.image

版权声明
本文为[June]所创,转载请带上原文链接,感谢