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 usebuilder_runner
- Re-usable
Transform
(known asConverter
in json_annotation) withgeneric
- 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() };
- 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 }
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());
}
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;
}
}