Skip to content

Commit 721b64e

Browse files
committed
start trying to handle custom key converters to json string
1 parent a36f266 commit 721b64e

File tree

3 files changed

+40
-2
lines changed

3 files changed

+40
-2
lines changed

json_serializable/example/example.dart

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
// for details. All rights reserved. Use of this source code is governed by a
33
// BSD-style license that can be found in the LICENSE file.
44

5+
import 'dart:convert';
6+
57
import 'package:json_annotation/json_annotation.dart';
68

79
part 'example.g.dart';
@@ -15,7 +17,15 @@ class Person {
1517
/// exist or is empty.
1618
final DateTime? dateOfBirth;
1719

18-
Person({required this.firstName, required this.lastName, this.dateOfBirth});
20+
/// An example of a custom map like type with non-string key
21+
final Person2<int, String> person;
22+
23+
Person({
24+
required this.firstName,
25+
required this.lastName,
26+
this.dateOfBirth,
27+
required this.person,
28+
});
1929

2030
/// Connect the generated [_$PersonFromJson] function to the `fromJson`
2131
/// factory.
@@ -24,3 +34,18 @@ class Person {
2434
/// Connect the generated [_$PersonToJson] function to the `toJson` method.
2535
Map<String, dynamic> toJson() => _$PersonToJson(this);
2636
}
37+
38+
const jsonKeyType = 'jsonKeyType';
39+
40+
class Person2<@jsonKeyType K, V> {
41+
Person2({required this.name, required this.id});
42+
final V name;
43+
final K id;
44+
45+
factory Person2.fromJson(Map<String, dynamic> json,
46+
K Function(Object?) fromJsonK, V Function(Object?) fromJsonV) =>
47+
Person2(id: fromJsonK(json), name: fromJsonV(json));
48+
Object toJson(Object? Function(K) toJsonK, Object? Function(V) toJsonV) => {
49+
toJsonK(id): toJsonV(name),
50+
};
51+
}

json_serializable/example/example.g.dart

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

json_serializable/lib/src/type_helpers/json_helper.dart

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,12 @@ List<String> _helperParams(
157157
// TODO: throw here if `typeParamIndex` is -1 ?
158158
final typeArg = type.typeArguments[typeParamIndex];
159159
final body = execute(typeArg, _helperLambdaParam);
160-
args.add('($_helperLambdaParam) => $body');
160+
if (helperArg.element.declaration.metadata.any((md) => md.element?.displayName == 'jsonKeyType')){
161+
final newBody = _helperParams(execute, paramMapper, type, positionalParams, targetElement);
162+
args.add('($_helperLambdaParam) => $newBody /* todo json key */');
163+
} else {
164+
args.add('($_helperLambdaParam) => $body');
165+
}
161166
}
162167

163168
return args;

0 commit comments

Comments
 (0)