schultek / dart_mappable

Improved json serialization and data classes with full support for generics, inheritance, customization and more.
https://pub.dev/packages/dart_mappable
MIT License
145 stars 22 forks source link

Is it possible to decode a json list without using `MapperContainer`? #209

Closed rubenferreira97 closed 2 months ago

rubenferreira97 commented 2 months ago

In my project, I am using dart_mappable to facilitate JSON serialization and deserialization for my model classes. While the package works seamlessly for single object mapping with the MapperContainer, I expected a simplified way to handle lists of JSON objects without relying on MapperContainer.

@MappableClass()
class Person with PersonMappable {
  Person(this.name, this.age);
  final String name;
  final int age;
}

void main() {
  // decode from json string
  String json = '{"name": "Max", "age": 18}';
  Person person = PersonMapper.fromJson(json);

  // decode list from json string
  String jsonList = '[{"name": "Max", "age": 18}, {"name": "John", "age": 40}]';
  List<Person> persons = ...; // How to map json list to object list?

  // Seems advanced for such task
  PersonMapper.ensureInitialized();
  final persons2 = MapperContainer.globals.fromJson<List<Person>>(jsonList);
}

Is there any built in way to accomplish this?

schultek commented 2 months ago

I don't get why you are asking? You have the correct way right there.

Everything uses MapperContainer internally, even if you are not explicitly calling it.

If you want a 'less advanced' way do (jsonDecode(jsonList) as List).map((item => PersonMapper.fromMap(item)).toList()

rubenferreira97 commented 2 months ago

Thanks for the response @schultek. I was hoping the Mapper would generate a method to decode json arrays like:

List<T> Mapper.fromJsonArray(String json) { ... }

So we could use like:

final List<Person> persons = PersonMapper.fromJsonArray(json);

Json array literals are valid and some APIs return them. Would it be reasonable to add it to the generateStaticDecoders?

schultek commented 2 months ago

I have no plans to add a specific method for that.

scopendo commented 2 months ago

I had the same question today also. For people new to dart_mappable, the suggested approach seems like exposing an internal detail of the package. I had hoped for something like:

  static const fromMap = PersonMapper.fromMap;
  static const fromJson = PersonMapper.fromJson;
  static const fromJsonList = PersonMapper.fromJsonList; // returns List<Person>