Flutter Dio数据对象

时间:2019-12-25 06:50:22

标签: flutter dart 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())

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

0 个答案:

没有答案