fromJsonWith<T extends dynamic> static method
T
fromJsonWith<T extends dynamic>(})
Hydrate a RealmObject from JSON using explicit property names.
Note: Consider using fromEJson() instead for automatic nested object handling.
Provide create to construct a new instance of T.
For embedded objects, provide nested creators.
Example:
final person = RealmJson.fromJsonWith<Person>(
json,
() => Person(ObjectId(), '', 0),
['name', 'age', 'address'],
embeddedCreators: {
'address': (json) => Address(json['street'], json['city'])
}
);
Implementation
static T fromJsonWith<T extends RealmObject>(
Map<String, dynamic> json,
T Function() create,
List<String> propertyNames, {
Map<String, dynamic Function(Map<String, dynamic>)>? embeddedCreators,
}) {
final obj = create();
for (final name in propertyNames) {
if (!json.containsKey(name)) continue;
try {
final jsonValue = json[name];
// Handle embedded objects
if (embeddedCreators?.containsKey(name) == true &&
jsonValue is Map<String, dynamic>) {
final embedded = embeddedCreators![name]!(jsonValue);
RealmObjectBase.set(obj, name, embedded);
} else {
RealmObjectBase.set(
obj,
name,
_fromJsonValue(jsonValue, embeddedCreators),
);
}
} catch (_) {
// Property conversion failed - skip it
}
}
// Handle _id/id mapping
final id = json['_id'] ?? json['id'];
if (id != null) {
try {
RealmObjectBase.set(obj, 'id', _fromJsonValue(id, embeddedCreators));
} catch (_) {
try {
RealmObjectBase.set(obj, '_id', _fromJsonValue(id, embeddedCreators));
} catch (_) {}
}
}
return obj;
}