google / google/json_serializable.dart

Guidance on using `json_serializable` helper utilities

Open
#1,394 0 comments 1 reaction 0 assignees View on GitHub
Dominant language
Dart
Stars
1.6k
Forks
461
Avg merge
45m
Merged PRs (30d)
1

Description

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:

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

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

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

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

Iterable $IterableUserDtoFromJsonUtf8(Uint8List bytes) {
final content = utf8.decode(bytes);
final json = (jsonDecode(content) as List);
final castedJson = List>.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.

3. Determining what type casts should be used on the `dynamic` type, following a `jsonDecode` call.

Thanks so much in advance for any help here!

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.