json_serializable.dart icon indicating copy to clipboard operation
json_serializable.dart copied to clipboard

Guidance on using `json_serializable` helper utilities

Open pattobrien opened this issue 6 months ago • 0 comments

I'm working on a code-gen package that generates logic for decoding/encoding dart values based on a given Media (MIME) Types.

An example, for context:

@MediaEncoder(MediaType.jsonUtf8)
Uint8List userDtoToJsonUtf8(Iterable<UserDto> value) => $IterableUserDtoToJsonUtf8(value);

@MediaDecoder(MediaType.jsonUtf8)
Iterable<UserDto> userDtoFromJsonUtf8(Uint8List bytes) =>
    $IterableUserDtoFromJsonUtf8(bytes);

// -- the above generates the below utils --

Uint8List $IterableUserDtoToJsonUtf8(Iterable<UserDto> value) {
  final json = value.map((e) => e.toJson()).toList();
  final jsonContent = jsonEncode(json);
  return utf8.encode(jsonContent);
}

Iterable<UserDto> $IterableUserDtoFromJsonUtf8(Uint8List bytes) {
  final content = utf8.decode(bytes);
  final json = (jsonDecode(content) as List);
  final castedJson = List<Map<String, dynamic>>.from(json);
  return castedJson.map((e) => UserDto.fromJson(e));
}

I started looking through the contents of this package, figuring that things would be a lot more robust if I could tap into json_serializable utilities instead of rolling my own. From my initial look though, I'm not quite sure those utilities were designed for external use, despite being public, so I wanted to check here before going any deeper.

Would anyone be able to point me in the right direction of any of the following utilities, if they exist?

  1. determine if a given type supports serialization/deserialization (primative types, specialized types like DateTime/Uri/etc, annotated jsonSerializable types.

  2. convert a given DartType to its respective conversion expression, e.g.

  • List => "foo.map((e) => Foo.fromJson(e))"
  • int/num/double => "int.parse" / "double.parse" etc.
  • class annotated with JsonSerializable => "Foo.fromJson(e)"
  • etc.
  1. Determining what type casts should be used on the dynamic type, following a jsonDecode call.

Thanks so much in advance for any help here!

pattobrien avatar Jan 30 '24 05:01 pattobrien