google / built_collection.dart

Immutable Dart collections via the builder pattern.
https://pub.dev/packages/built_collection
BSD 3-Clause "New" or "Revised" License
275 stars 53 forks source link

[Feature Request/ Question] Native Support for json_serializable / json_annotation #260

Open MSCL opened 2 years ago

MSCL commented 2 years ago

It would be great when the package natively works together with the

packages for model and entity classes. Currently I have to write some boilerplate code to make it work.

Or is this already working and I just missed it?

davidmorgan commented 2 years ago

Let's ask :)

@kevmoo is there something I can do here to integrate with json_serializable? Thanks :)

kevmoo commented 2 years ago

@davidmorgan – I don't know! 🤷 – @MSCL – could you expand?

MSCL commented 2 years ago

@kevmoo @davidmorgan Sorry for the late reply!

So, currently I had to do this to make it work for a BuiltList of type String:

import 'package:built_collection/built_collection.dart';
import 'package:json_annotation/json_annotation.dart';

class StringBuiltListConverter extends BuiltListConverter<String> {
  const StringBuiltListConverter();
}

abstract class BuiltListConverter<T>
    implements JsonConverter<BuiltList<T>, List<dynamic>> {
  const BuiltListConverter();

  @override
  BuiltList<T> fromJson(List<dynamic> json) => BuiltList<T>(json);

  @override
  List<dynamic> toJson(BuiltList<T> instance) => instance.toList();
}

For every BuiltList type (int, double, custom data type) you would have to create a new specific BuiltListConverter class. Not too much boilerplate code in the end. But normally the BuiltList could implement the JsonConverter interface by default and just point to the 'toList()' or sth. . Similar to my solution here maybe?