fromJson<T extends Serializable> method

T fromJson<T extends Serializable>(
  1. Map<String, dynamic> json, {
  2. T? notAvailable,
})

Deserialize json based on its type T.

Returns the deserialized object if the type T has been registered in this factory. If the type is not available (registered), notAvailable is returned if specified. Otherwise, a SerializationException is thrown.

Implementation

T fromJson<T extends Serializable>(
  Map<String, dynamic> json, {
  T? notAvailable,
}) {
  var message = '';
  final type = json[Serializable.CLASS_IDENTIFIER];
  if (!_registry.containsKey(type)) {
    message =
        "A 'fromJson' function was not found in the FromJsonFactory for the type '$type'. "
        "Register a Serializable class using the 'FromJsonFactory().register()' method."
        "\nIf you are using CARP Mobile Sensing, you can ensure json initialization by calling"
        "'CarpMobileSensing.ensureInitialized()' as part of your main method.";

    if (notAvailable != null) {
      debugPrint('$runtimeType - $message');
      return notAvailable;
    } else {
      throw SerializationException(message);
    }
  }

  var fromJson = Function.apply(_registry[type!]!, [json]);
  if (fromJson is T) return fromJson;

  message =
      "The 'fromJson' function registered for the type '$type' does not return an object of the correct type ('$T'). "
      "Make sure that the fromJson function returns a class of type '$T'.";

  if (notAvailable != null) {
    debugPrint('$runtimeType - $message');
    return notAvailable;
  } else {
    throw SerializationException(message);
  }
}