object_mapper 1.0.0+2

Flutter Android iOS web

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 object or nested object
void mapping(Mapper map) {
 map<ObjectClass>("field", 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;
  }
}
4
likes
90
pub points
66%
popularity

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)
View/report issues

Documentation

API reference

Uploader

markgravity.in@gmail.com

License

MIT (LICENSE)

Dependencies

flutter

More

Packages that depend on object_mapper