2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FlutterでJsonをパースする

Last updated at Posted at 2020-05-19

今回はjson_annotationを利用してパースメソッドを自動生成します。

まずは以下をpub spec.yamlに追加します。

json_serializable: ^3.3.0
json_annotation: ^3.0.1

次に任意のEntityオブジェクトを作成します。

class User {
  final String id;
  final String name;

  User(this.id, this.name);
}

作成したオブジェクトのファイルの先頭にpart “[任意のクラス].g.dart”を追加します。

part 'user.g.dart';

追加後にプロジェクトのルートで以下のコマンドを実行します。

flutter packages pub run build_runner build

実行後にパース用のメソッドが自動生成されます。

Entityクラスに以下のような関数を追加して利用します。

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

面倒なJSONのパースを半自動化できるのでとてもおすすめです。
早くDartにもCodableのような機能が実装されるといいなと思いました。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?