fromEJsonMap<T extends dynamic> static method

T fromEJsonMap<T extends dynamic>(
  1. Map<String, dynamic> json, {
  2. T create()?,
  3. List<String>? propertyNames,
  4. Map<String, dynamic Function(Map<String, dynamic>)>? embeddedCreators,
})

Deserialize a RealmObject from JSON using generated fromEJson() method.

This is the recommended deserialization method as it:

  • Automatically handles nested RealmObjects
  • Supports both plain JSON and MongoDB extended JSON (EJson) format
  • Matches the capabilities of toEJson() for round-trip serialization
  • Handles all Realm types including DateTime, ObjectId, collections, etc.

Important: Schema must be initialized before calling this method:

ChatUser.schema;
ChatRoom.schema;

final room = RealmJson.fromEJsonMap<ChatRoom>(jsonData);

Accepts plain JSON (from MongoDB or RealmJson.toJsonWith):

  • {"updatedOn": "2025-11-28T14:30:04.025Z"} → automatically converts to EJson

Falls back to fromJsonWith if fromEJson() is not available.

Implementation

static T fromEJsonMap<T extends RealmObject>(
  Map<String, dynamic> json, {
  T Function()? create,
  List<String>? propertyNames,
  Map<String, dynamic Function(Map<String, dynamic>)>? embeddedCreators,
}) {
  try {
    // Convert plain JSON to EJson format (reverse of _ejsonToPlain)
    final ejsonData = _plainToEJson(json);

    // Use generated fromEJson() function from realm_common
    // This is a global function that requires schema registration
    return fromEJson<T>(ejsonData);
  } catch (e) {
    // Attempt a second pass: if id/_id are hex or UUID strings, encode to extended EJSON
    try {
      final adjusted = _withIdAsExtendedJson(json);
      final ejsonData2 = _plainToEJson(adjusted);
      return fromEJson<T>(ejsonData2);
    } catch (_) {
      // Fall back to manual deserialization if hints are provided
      if (create != null && propertyNames != null) {
        return fromJsonWith<T>(
          json,
          create,
          propertyNames,
          embeddedCreators: embeddedCreators,
        );
      }
      rethrow;
    }
  }
}