Flutter- JSON parsing framework using method json_serializable

For now, the communication content data format of most API network requests is JSON. All JSON returns are strings. If you want to get the id in the data, it is definitely not possible to directly intercept the string. It must be parsed into a Map or object in a certain way, and then processed. Like some simple APIs, with fewer fields and layers, you can choose to parse the data into a Map.

insert image description here

The Dart language itself has a default library to parse it into a Map. Here I refer to a third-party framework to parse it into objects in data, which is more convenient to use. There are actually many ways to parse JSON in the Dart language. json_serializableThe library [ ] ( official website portal ) I use is officially written by Google.

insert image description here

Put under the hierarchy in json_serializable: ^6.6.1the project file , remember to place an indent, and then remember to pull the dependencies.pubspec.yamldev_dependenciesPub get

insert image description here
Use:
Step 1: Create a file with a library of annotated JsonSerializableclasses GoodsDetailData(classes defined by yourself) dart, define the file name yourself, here is goods_detail_data.dart

import 'package:json_annotation/json_annotation.dart';

part 'goods_detail_data.g.dart';

@JsonSerializable()
class GoodsDetailData {
  final int id;
  final String createdAt;
  final String title;


  GoodsDetailData({required this.id,  required this.createdAt, required this.title});


  factory GoodsDetailData.fromJson(Map<String, dynamic> json) => _$GoodsDetailDataFromJson(json);

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

Step 2: pubspec.yamlAdd a command-line tool build_runner ( official website portal ) in the file, which is also added dev_dependenciesunder the level.

insert image description here
Pub getIn the future, execute flutter pub run build_runner buildthe command in the terminal under the root directory to generate goods_detail_data.g.dartthe file

flutter pub run build_runner build

insert image description here
insert image description here

Note ❗️: The field names returned by JSON are lowercase and underscored, while we write in the model in humpcase, and the recommended variables and class names in Dart are all in camelcase, so it must be configured through a certain mechanism to specify the corresponding fields for it to parse.@JsonKey

@JsonKey(name: "created_at")

If you change the model file, you need to run flutter pub run build_runner buildthe command again

insert image description here

insert image description here

In the page use:

  /// 解析商品详情JSON
  void _ParseGoodsDetailJSON() async {
    // var response =
    //     await dio.get('http://my-cloud-music-api-sp3-dev.ixuea.com/v1/goods/6');
    // var jsonString = response.data.toString();

    var jsonString =
        '{"data":{"id": "6","created_at": "2300-09-24T22:47:54.000Z","title": "华为笔记本电脑MateBook14"},"status":0}';

    ///解析为map
    Map<String, dynamic> map = json.decode(jsonString);

    var data = GoodsDetail.fromJson(map);
    debugPrint(data.data!.title);
  }
}

insert image description here

Guess you like

Origin blog.csdn.net/m0_48259951/article/details/129194878
Recommended