Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Realm Database

Serialization - Flutter SDK

El Atlas Device SDK para Flutter admite la serialización y deserialización de JSON extendido (EJSON) hacia y desde objetos Realm estáticos.

El SDK de Flutter actualmente soporta la serialización de los siguientes tipos de datos soportados:

  • All Dart-language data types

  • All Realm-specific data types, except Decimal128 and RealmValue

La siguiente tabla ilustra cómo los tipos de datos específicos de Realm del SDK se serializan con ejemplos de salida:

Tipo de Realm
Serializa a

Fecha y hora

fecha

DateTime birthDate = DateTime.utc(2024, 4, 10) se serializa a birthDate: {$date: {$numberLong: 1712707200000}}

RealmList

Arreglo

List<String> listOfStrings = [food, water] se serializa a listOfStrings: [food, water]

RealmMap

Arreglo

Map<String, int> mapOfMixedAnyValues = {'first': 123 , 'second': 567} se serializa a mapOfValues: {first: {$numberInt: 123}, second: {$numberInt: 567}}

RealmSet

Arreglo

Set<int> setOfInts = {0, 1, 2, 3} se serializa a setOfInts: [{$numberInt: 0}, {$numberInt: 1}, {$numberInt: 2}, {$numberInt: 3}]

ObjectId

ObjectId

ObjectId id = ObjectId() se serializa a {id: {$oid: 666a6fd54978af08e54a8d52}

UUID

Binario

Uuid myId = Uuid.v4() se serializa a myId: {$binary: {base64: 6TvsMWxDRWa1jSC6gxiM3A==, subType: 04}}

Uint8List

Binario

Uint8List aBinaryProperty = Uint8List.fromList([1, 2]) se serializa a aBinaryProperty: {$binary: {base64: AQI=, subType: 00}}

Objeto

Documento

Address address = Address("500 Dean Street", "Brooklyn", "NY", "USA") se serializa a address: {street: 500 Dean Street, city: Brooklyn, state: NY, country: USA}

For more information on the serialization of non-Realm specific types, see BSON Data Types and Associated Representations.

Flutter SDK serialization does not currently support the following BSON types: Code, CodeWScope, DBPointer, DBRef, Regular Expression, and Timestamp.

The SDK's full-document encoder enables you to serialize and deserialize user-defined classes.

To use the encoder, create your object model as you normally would using the @RealmModel() annotation. The RealmObject class model created by your part declaration provides the necessary methods for serialization and deserialization.

The following Pet object model will be used in the examples on this page:

import 'package:realm_dart/realm.dart';
part 'pet.realm.dart';
@RealmModel()
class _Pet {
late String type;
late int numberOfLegs;
late DateTime birthDate;
late double? price;
}

Para objetos basados ​​en RealmObject clases, puede serializarlos en EJSON usando toEjson() método de las dos maneras siguientes:

// Pass the object as a parameter to the method
EJsonValue serializeByParam = toEJson(spider);
// Call the method directly on the object
EJsonValue serializeWithCall = spider.toEJson();
{
type: Jumping Spider,
numberOfLegs: {$numberInt: 8},
birthDate: {$date: {$numberLong: 1712707200000}},
price: null
}

Deserialice desde EJSON usando el método fromEjson(). El método toma EJSON para un tipo de objeto Realm específico como entrada y emite una instancia deserializada del tipo de objeto Realm específico.

The following example deserializes serializeByParam from the previous example:

// Pass the serialized object to the method
final deserializeFromEjsonWithExplicitType = fromEJson<Pet>(serializeByParam);
// The method can also infer the object type
Pet deserializeFromEjson = fromEJson(serializeByParam);

Para clases que no sean de Realm, se puede usar la anotación @ejson en el constructor de la clase para generar un decodificador y un codificador:

class Person {
final String name;
final DateTime birthDate;
final int? age;
final double income;
final Person? spouse;
@ejson // annotate constructor to generate decoder and encoder
Person(this.name, this.birthDate, this.income, {this.spouse, this.age});
}

The SDK also supports custom EJSON codecs. To use them in your app, register the custom EJSON encoder and decoder for the specified type.

Volver

Freeze Data

En esta página