toJson<T extends Object?> static method

T toJson<T extends Object?>(
  1. Object? data, {
  2. Object? reviver(
    1. Object?,
    2. Object?
    )?,
  3. JsonDecodeOptions? options,
})

Converts a JSON-encoded string to a Dart object represented as a Map.

The input data is a JSON-encoded string. Returns a Map representing the Dart object.

Implementation

static T toJson<T extends Object?>(
  Object? data, {
  Object? Function(Object?, Object?)? reviver,
  JsonDecodeOptions? options,
}) {
  if (data is! String) {
    try {
      return JsonParser.valueAs<T>(data);
    } catch (_) {
      throw CoreErrors.invalidOperationArguments(
        "toJson",
        name: "data",
        reason: "Invalid data encountered during JSON conversion.",
      );
    }
  }
  final decode = JsonCodec.jsonDecode(
    data,
    reviver: reviver,
    options: options,
  );
  try {
    return JsonParser.valueAs<T>(decode);
  } on BuError {
    rethrow;
  } catch (_) {
    throw CoreErrors.invalidOperationArguments(
      "toJson",
      name: "data",
      reason: "Failed to cast json to $T.",
    );
  }
}