Flutter 開発の実践 - jsontodart と Dart Model クラスの生成

Flutter 開発実践 - jsontodart と Dart Model クラスを生成します。
開発では、要求されたデータ Json をモデル クラスに変換する必要があることがよくあります。以下は、Jsontodart が Dart Model クラスを生成する方法の記録です。

1. JSONはDart Modelクラスを生成します

開発では、json をマップまたはリストに変換するためによく使用されます。
json.decode() を介して、JSON 文字列を次のようなリスト/マップに変換すると便利です。

{
    
    
  "name": "Bruce",
  "age": 20
}

マップに変換

Map<String, dynamic> user = json.decode(json);

多くの場合、リクエストはカスタム クラスにカプセル化され、最終的にリクエストは Map に変換され、Dio を通じてサーバーにリクエストされます。

class UserInfoReq {
    
    
  int? id;
  int? timestamp;

  UserInfoReq(
      {
    
    this.id, this.timestamp});

  UserInfoReq.fromJson(Map<String, dynamic> json) {
    
    
    id = json['id'];
    timestamp = json['timestamp'];
  }

  Map<String, dynamic> toJson() {
    
    
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['timestamp'] = this.timestamp;
    return data;
  }
}

json_annotation、json_serializable、build_runner プラグインを使用して、Json に対応する Dart モデルを生成します。

1. プラグイン json_annotation、json_serializable、build_runner の導入

対応するプラグイン json_annotation、json_serializable、build_runner を pubspec.yaml に導入します。

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

  # JSON注解
  json_annotation: ^4.8.0

dev_dependencies:
  flutter_test:
    sdk: flutter

  # JSON转model
  json_serializable: ^6.6.1
  build_runner: ^2.3.3

2. Json を Dart に変換する

Jsontodart は開発でよく使用されます。ここに 2 つあります
https://javiercbk.github.io/json_to_dart/
https://caijinglong.github.io/json2dart/index_ch.html

次の Json を対応するクラスに変換します

{
    
    
"name":"Bruce",
"age":20
}

対応ダーツクラス

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


()
  class UserInfoDto extends Object {
    
    

  (name: 'name')
  String name;

  (name: 'age')
  int age;

  UserInfoDto(this.name,this.age,);

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

  Map<String, dynamic> toJson() => _$UserInfoDtoToJson(this);

}

ここではjson_annotationを使用しているため、コマンドを使用して「user_info_dto.g.dart」ファイルを生成する必要があります

プロジェクトのルート ディレクトリで実行すると、次のようになります。

flutter packages pub run build_runner build

これにより、ワンタイム ビルドがトリガーされ、必要に応じて Model の json シリアル化コードを生成できます。ソース ファイルを使用して、Model クラス (@JsonSerializable アノテーションを含む) を生成する必要があるソース ファイルを見つけて、対応する .g を生成します。ダーツファイル。

ここに画像の説明を挿入

3. まとめ

Flutter 開発実践 - jsontodart と Dart Model クラスを生成します。json_annotation、json_serializable、build_runner プラグインを使用して、Json に対応する Dart モデルを生成します。

学習記録、日々改善を続けてください。

おすすめ

転載: blog.csdn.net/gloryFlow/article/details/131927545