首页 > 解决方案 > Flutter Dio 数据对象

问题描述

我想知道我做的对不对?我通过辅助函数将我的 json_annotation 对象转换为 Map,然后将其发送到 Dio 数据参数

dynamic jsonify(dynamic jsonValue, {bool includeNull = false}) {
final Map<String, dynamic> map = <String, dynamic>{};
try {
  if (jsonValue is String &&
      json.decode(jsonValue) is Map<String, dynamic>) {
    final Map<String, dynamic> tempMap = json.decode(jsonValue);
    tempMap.removeWhere(
        (String key, dynamic value) => !includeNull && value == null);
    tempMap.forEach((String key, dynamic value) {
      final dynamic jsonValue = jsonify(value, includeNull: includeNull);
      tempMap.update(key, (dynamic existingValue) => jsonValue);
    });
    map.addAll(tempMap);
  } else if (jsonValue is List<dynamic>) {
    for (int i = 0; i < jsonValue.length; i++) {
      jsonValue[i] = jsonify(jsonValue[i], includeNull: includeNull);
    }
    return jsonValue;
  } else {
    return jsonValue;
  }
} on FormatException {
  return jsonValue;
}
return map;  }

我的 json_annotation 对象

@JsonSerializable()
class TripCloseRequest implements Requestable {
  /// the constructor to the response of the tours api
  TripCloseRequest({this.data});

  /// factory constructor for response of api
  factory TripCloseRequest.fromJson(Map<String, dynamic> json) =>
      _$TripCloseRequestFromJson(json);

  /// convert the model to json
  String toJson() => json.encode(_$TripCloseRequestToJson(this));

  ///data - api request data model
  @JsonKey(name: 'data')
  final TripCloseDetails data;

  /// function that converts the request model to form data
  @override
    Map<String, dynamic> toData() => jsonify(toJson());
}

这是我的 Dio 电话

client.post<dynamic>(_urlCloseTrip, data: tripCloseRequest.toData())

颤振 JSON 注释是否可以替代我的辅助函数 jsonify?

标签: flutterdartdio

解决方案


推荐阅读