object_mapper

Creator: coderz1093

Last updated:

Add to Cart

Description:

object mapper

Object Mapper #


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 {
//
}

copied to clipboard

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);
}
}

copied to clipboard


Step 3: Register factory for new model into Mappable.factories
Mappable.factories = {
TestInfo: () => TestInfo()
};
copied to clipboard


Usage #

Map to Object

final json = {
"id" : 2
};

final info = Mapper.fromJson(json).toObject<TestInfo>();
print(info.id); // 2
copied to clipboard

Object to Map

final info = TestInfo();
info.id = 2;
final json = info.toJson();
print(json); // { "id": 2 }
copied to clipboard
Map - Use Cases #

int, string, numeric, bool

void mapping(Mapper map) {
map("field", field, (v) => field = v);
}
copied to clipboard

List of number or bool

void mapping(Mapper map) {
map("field", field, (v) => field = v.cast<int>());
}
copied to clipboard

List of object or nested object

void mapping(Mapper map) {
map<ObjectClass>("field", field, (v) => field = v);
}
copied to clipboard

Nested json

void mapping(Mapper map) {
map<ObjectClass>("field1.field2.field3", field, (v) => field = v);
}
copied to clipboard

With transform, such as DateTransform, EnumTransform

DateTime time;
void mapping(Mapper map) {
map("time", time, (v) => time = v, DateTransform());
}
copied to clipboard
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;
}
}
copied to clipboard

License

For personal and professional use. You cannot resell or redistribute these repositories in their original state.

Customer Reviews

There are no reviews.