Flutter uses json_serializable and build_runner to automatically parse JSON

Small partners familiar with front-end development must be accustomed to mapping JSON into entity class first-time flutter through some third-party plug-ins, which can be painful when you try to parse json.

Because flutter itself does not provide similar functionality, of course, it's a tough question for our powerful hands-on buddies.

Now I'll show you how to automatically convert JSON data into our entity classes through json_serializable and build_runner libraries.

First, we need to integrate these two libraries in our pubspace.yaml file:

    sdk: flutter
  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  dio: 2.1.13
  build_runner: 1.6.6
  json_serializable: 3.2.0

Little buddies can go github perhaps pub.dev Check out the latest versions in these two places

Next we need to prepare a json file:

  "GoodsMode": {
    "banner": [
        "image": "http://images.baixingliangfan.cn/compressedPic/20181210150050_5409.jpg"
        "image": "http://images.baixingliangfan.cn/compressedPic/20181210150050_5409.jpg"
        "image": "http://images.baixingliangfan.cn/compressedPic/20181210150050_5409.jpg"
    "goods": [
        "image": "http://images.baixingliangfan.cn/homeFloor/20190116/20190116133522_9332.jpg",
        "goodsId": "faa86c6ee451445a9475870656f04192"
        "image": "http://images.baixingliangfan.cn/homeFloor/20190116/20190116135616_4151.jpg",
        "goodsId": "80817b9fd00b48f296ce939ae197030b"
        "image": "http://images.baixingliangfan.cn/homeFloor/20190116/20190116133626_1248.jpg",
        "goodsId": "00cee04d12474910bfeb7930f6251c22"
        "image": "http://images.baixingliangfan.cn/homeFloor/20190116/20190116133740_8452.jpg",
        "goodsId": "bdfa9a9a358f436594a740e486fd2060"
        "image": "http://images.baixingliangfan.cn/homeFloor/20190116/20190116133753_7874.jpg",
        "goodsId": "516f9db6ee8e499cb8a8758cf2e567c7"

Then we need to write the entity class:

import 'package:json_annotation/json_annotation.dart';
part 'goods_model.g.dart';
class GoodsMode extends Object {
  @JsonKey(name: 'banner')
  List<Banner> banner;
  @JsonKey(name: 'goods')
  List<Goods> goods;
  factory GoodsMode.fromJson(Map<String, dynamic> srcJson) => _$GoodsModeFromJson(srcJson);
  Map<String, dynamic> toJson() => _$GoodsModeToJson(this);

class Banner extends Object {
  @JsonKey(name: 'image')
  String image;
  factory Banner.fromJson(Map<String, dynamic> srcJson) => _$BannerFromJson(srcJson);
  Map<String, dynamic> toJson() => _$BannerToJson(this);

class Goods extends Object {
  @JsonKey(name: 'image')
  String image;
  @JsonKey(name: 'goodsId')
  String goodsId;
  factory Goods.fromJson(Map<String, dynamic> srcJson) => _$GoodsFromJson(srcJson);
  Map<String, dynamic> toJson() => _$GoodsToJson(this);


Here are some key points:

1. You need to import the json_annotation.dart file at the top

2. You need to write part'xxx.g.dart', where XXX represents the dart file name of your entity class, such as the example above.

The body class is goods_model.dart, which should be written as goods_model.g.dart.


Fields in json can be renamed by @Jsonkey. For example, the server returns a field name called goods_name.

But I want to use hump labeling in the created entity class, and then I can write as follows:

@JsonKey(name: 'goods_name')

    String goodsName;

Of course, it's OK not to write @JsonKey.

4. A factory method needs to be washed here. The format should be underlined and the beginning of the dollar sign.


Then I write a method of turning json, which starts with an underscore and a dollar sign.


At this point, you will find that the entity class you created has a bunch of red errors, which are ignored temporarily.

@ The JsonSerializable() annotation supports the configuration of the required parameters. This is its default configuration, which is of interest.

Partners can study the source code and compose their own parsing patterns.

static const defaults = JsonSerializable(
  anyMap: false,
  checked: false,
  createFactory: true,
  createToJson: true,
  disallowUnrecognizedKeys: false,
  explicitToJson: false,
  fieldRename: FieldRename.none,
  ignoreUnannotated: false,
  includeIfNull: true,
  nullable: true,

Now that the data is ready, we can enter it at the command line in the project directory:

flutter packages pub run build_runner build

When the code is executed, the red error disappears and is automatically generated under the folder of the entity class.

xxx.g.dart file. Next we can request the interface in the familiar way before, and then we can get the data.

By passing json data to the factory method, the data is automatically parsed


Future<HomePageModel> getHomeData() async {
  HomePageModel homePageModel;
  var data = await getHomePageContent();
  var jsonObject = json.decode(data);
  if (jsonObject is Map) {
    homePageModel = GoodsModel.fromJson(jsonObject['data']);
  return homePageModel;

Of course, it's a bit tiring to write entity classes manually. Here's one https://caijinglong.github.io/json2dart/index_ch.html You can paste json directly into the web site, which will automatically generate the corresponding entity class.

But there is a small problem with this website, that is, it will not automatically use the same model in json, which is also a small defect.

Keywords: JSON github SDK iOS

Added by adiwood on Thu, 22 Aug 2019 14:38:21 +0300