object_mapper 1.2.1 copy "object_mapper: ^1.2.1" to clipboard
object_mapper: ^1.2.1 copied to clipboard

Object Mapper is a package written in Dart that makes it easy for you to convert your model objects to and from JSON.

Object Mapper #

Coverage GitHub issues GitHub stars GitHub license


A package written in Dart that makes it easy for you to convert your model objects to and from JSON. It's inspired by ObjectMapper

object_mapper vs json_annotation

  • No extras file (*.g.dart), no need to use builder_runner
  • Re-usable Transform (known as Converter in json_annotation) with generic

Implement #

  • Step 1: Extend your class with Mappable mixin
class TestInfo with Mappable {
    //
}

  • Step 2: Override Mappable.mapping method & add your map functions. Check more use cases here
class TestInfo with Mappable {
 int id;
  
 @override
 void mapping(Mapper map) {
  map("id", id, (v) => id = v);
 }
}

  • Step 3: Register factory for new model into Mappable.factories

    Mappable.factories = {
      TestInfo: () => TestInfo()
    };
    

Usage #

  • Map to Object
final json = {
 "id" : 2
};

final info = Mapper.fromJson(json).toObject<TestInfo>();
print(info.id); // 2
  • Object to Map
final info = TestInfo();
info.id = 2;
final json = info.toJson();
print(json); // { "id": 2 }

Map - Use Cases #

  • int, string, numeric, bool
void mapping(Mapper map) {
 map("field", field, (v) => field = v);
}
  • List of number or bool
void mapping(Mapper map) {
 map("field", field, (v) => field = v.cast<int>());
}
  • List of object or nested object
void mapping(Mapper map) {
 map<ObjectClass>("field", field, (v) => field = v);
}
  • Nested json
void mapping(Mapper map) {
 map<ObjectClass>("field1.field2.field3", field, (v) => field = v);
}
  • With transform, such as DateTransform, EnumTransform
DateTime time;
void mapping(Mapper map) {
 map("time", time, (v) => time = v, DateTransform());
}

Custom transform #

Implement your class with Transformable

class EnumTransform<Object extends Enumerable, JSON>
    with Transformable<Object, JSON> {
  Object fromJson(value) {
    if (value == null || !(value is JSON)) return null;
    return RawRepresentable(Object, value);
  }

  JSON toJson(Object value) {
    if (value == null) return null;
    return value.rawValue;
  }
}
12
likes
140
points
2.7k
downloads

Publisher

unverified uploader

Weekly Downloads

Object Mapper is a package written in Dart that makes it easy for you to convert your model objects to and from JSON.

Repository (GitHub)

Documentation

API reference

License

MIT (license)

Dependencies

flutter

More

Packages that depend on object_mapper