Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Guidance on using json_serializable helper utilities #1394

Open
pattobrien opened this issue Jan 30, 2024 · 0 comments
Open

Guidance on using json_serializable helper utilities #1394

pattobrien opened this issue Jan 30, 2024 · 0 comments

Comments

@pattobrien
Copy link

pattobrien commented Jan 30, 2024

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant