felangel / data_class

Experimental support for data classes in Dart using macros.
https://pub.dev/packages/data_class
MIT License
295 stars 10 forks source link

feat: some version of serialisation #35

Closed azeldaniel closed 4 months ago

azeldaniel commented 4 months ago

Description

Data classes are usually converted to a more generic form (string or map) when interacting with external libraries. I'm not sure of the scope of this library, but a feature to serialise the data classes would be great. It does not have to be a complete solution to compete with other emerging libraries, but complete enough to coexist with existing data_class constructors and toString methods.

Desired Solution

A feature to serialise the attributes of a data class.

import 'package:data_class/data_class.dart';

@Data()
class Person {
  final String name;
}

void main() {
  // 🪨 Create a const instance with required, name parameters.
  const dash = Person(name: 'Dash');

  // Serialise
  print(dash.toMap()); // {name: Dash} OR
  print(dash.toJson(); // {"name": "Dash"}

  // Deserialise 
  final sam = Person.fromMap({'name': 'Sam'}); // OR
  final john = Person.fromJson('{"name": "John"}');
}

Alternatives Considered

Using the json package; however, it currently has limitations on enums, dynamic values, date time etc.

felangel commented 4 months ago

Hi @azeldaniel 👋 Thanks for opening an issue!

This seems to be a duplicate of https://github.com/felangel/data_class/issues/5. In my experience data classes and serialization are not tightly coupled and I'd prefer to delegate serialization and deserialization to specialized packages. I'm sure either package:json will eventually address the limitations you've specified since it's still early and macros aren't stable.

Hope that helps! Closing for now but happy to continue the conversation if you have additional thoughts/feedback, thanks!