toJson<T extends Object?> static method

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

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,
}) {
  if (data is! String) {
    try {
      return JsonParser.valueAs<T>(data);
    } catch (_) {
      throw ArgumentException.invalidOperationArguments(
        "toJson",
        name: "data",
        reason: "Invalid data encountered during JSON conversion.",
      );
    }
  }
  final decode = jsonDecode(data, reviver: reviver);
  try {
    return JsonParser.valueAs<T>(decode);
  } catch (_) {
    throw ArgumentException.invalidOperationArguments(
      "toJson",
      name: "data",
      reason: "Failed to casting json as $T.",
    );
  }
}