getJson<T> method

Future<ClientResult> getJson<T>({
  1. required String url,
  2. required T fromJson(
    1. Map<String, dynamic> json
    ),
  3. required OnSuccessTyped<T> onSuccess,
  4. required OnError onError,
  5. Map<String, String>? headers,
  6. Map<String, String>? queryParameters,
  7. Duration? timeout,
  8. ClientType? clientType,
  9. String? cancelKey,
  10. OnHttpError? onHttpError,
  11. Map<int, OnStatus>? onStatus,
  12. Set<int>? successCodes,
  13. Set<int>? errorCodes,
})

Performs a GET request with typed JSON response.

Automatically parses the response body as JSON and deserializes it using the provided fromJson function.

Implementation

Future<ClientResult> getJson<T>({
  required String url,
  required T Function(Map<String, dynamic> json) fromJson,
  required OnSuccessTyped<T> onSuccess,
  required OnError onError,
  Map<String, String>? headers,
  Map<String, String>? queryParameters,
  Duration? timeout,
  ClientType? clientType,
  String? cancelKey,
  OnHttpError? onHttpError,
  Map<int, OnStatus>? onStatus,
  Set<int>? successCodes,
  Set<int>? errorCodes,
}) async {
  return get(
    url: url,
    headers: headers,
    queryParameters: queryParameters,
    timeout: timeout,
    clientType: clientType,
    cancelKey: cancelKey,
    onSuccess: (response) {
      try {
        final json = response.jsonBody;
        if (json == null) {
          onError(ClientException(
            message: 'Invalid JSON response',
            url: url,
            type: ClientErrorType.badResponse,
            responseBody: response.body,
          ));
          return;
        }
        final data = fromJson(json);
        onSuccess(data, response);
      } catch (e) {
        onError(ClientException(
          message: 'Failed to parse JSON: $e',
          url: url,
          type: ClientErrorType.unknown,
          originalError: e,
        ));
      }
    },
    onError: onError,
    onHttpError: onHttpError,
    onStatus: onStatus,
    successCodes: successCodes,
    errorCodes: errorCodes,
  );
}