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.
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_serializable
The library [ ] ( official website portal ) I use is officially written by Google.
Put under the hierarchy in json_serializable: ^6.6.1
the project file , remember to place an indent, and then remember to pull the dependencies.pubspec.yaml
dev_dependencies
Pub get
Use:
Step 1: Create a file with a library of annotated JsonSerializable
classes 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.yaml
Add a command-line tool build_runner ( official website portal ) in the file, which is also added dev_dependencies
under the level.
Pub get
In the future, execute flutter pub run build_runner build
the command in the terminal under the root directory to generate goods_detail_data.g.dart
the file
flutter pub run build_runner build
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 build
the command again
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);
}
}