Skip to content

Commit f8dc218

Browse files
authored
changelog cleanup, add more examples to readme (#1213)
1 parent aee8507 commit f8dc218

File tree

9 files changed

+239
-36
lines changed

9 files changed

+239
-36
lines changed

json_annotation/lib/src/json_converter.dart

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,16 +26,15 @@
2626
///
2727
/// ```dart
2828
/// @JsonSerializable()
29-
/// @MyJsonConverter()
3029
/// class Example {
3130
/// @MyJsonConverter()
3231
/// final Value property;
3332
/// }
3433
/// ```
3534
///
36-
/// Or finally, passed to the annotation:
35+
/// Or finally, passed to the `@JsonSerializable` annotation:
3736
///
38-
///```dart
37+
/// ```dart
3938
/// @JsonSerializable(converters: [MyJsonConverter()])
4039
/// class Example {}
4140
/// ```

json_serializable/CHANGELOG.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
## 6.4.2-dev
22

3-
- Support `ConstructorElement` which allows using tear-off constructors.
3+
- Allow constructors to be passed to `JsonKey` parameters that support
4+
`Function` types.
45

56
## 6.4.1
67

json_serializable/README.md

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,15 +171,94 @@ customize the encoding/decoding of any type, you have a few options.
171171
`toJson()` function to the type. Note: while you can use `json_serializable`
172172
for these types, you don't have to! The generator code only looks for these
173173
methods. It doesn't care how they were created.
174+
175+
```dart
176+
@JsonSerializable()
177+
class Sample1 {
178+
Sample1(this.value);
179+
180+
factory Sample1.fromJson(Map<String, dynamic> json) =>
181+
_$Sample1FromJson(json);
182+
183+
// Sample2 is NOT annotated with @JsonSerializable(), but that's okay
184+
// The class has a `fromJson` constructor and a `toJson` method, which is
185+
// all that is required.
186+
final Sample2 value;
187+
188+
Map<String, dynamic> toJson() => _$Sample1ToJson(this);
189+
}
190+
191+
class Sample2 {
192+
Sample2(this.value);
193+
194+
// The convention is for `fromJson` to take a single parameter of type
195+
// `Map<String, dynamic>` but any JSON-compatible type is allowed.
196+
factory Sample2.fromJson(int value) => Sample2(value);
197+
final int value;
198+
199+
// The convention is for `toJson` to take return a type of
200+
// `Map<String, dynamic>` but any JSON-compatible type is allowed.
201+
int toJson() => value;
202+
}
203+
```
204+
174205
1. Use the [`JsonKey.toJson`] and [`JsonKey.fromJson`] properties to specify
175206
custom conversions on the annotated field. The functions specified must be
176207
top-level or static. See the documentation of these properties for details.
208+
209+
```dart
210+
@JsonSerializable()
211+
class Sample3 {
212+
Sample3(this.value);
213+
214+
factory Sample3.fromJson(Map<String, dynamic> json) =>
215+
_$Sample3FromJson(json);
216+
217+
@JsonKey(
218+
toJson: _toJson,
219+
fromJson: _fromJson,
220+
)
221+
final DateTime value;
222+
223+
Map<String, dynamic> toJson() => _$Sample3ToJson(this);
224+
225+
static int _toJson(DateTime value) => value.millisecondsSinceEpoch;
226+
static DateTime _fromJson(int value) =>
227+
DateTime.fromMillisecondsSinceEpoch(value);
228+
}
229+
```
230+
177231
1. Create an implementation of [`JsonConverter`] and annotate either the
178232
corresponding field or the containing class. [`JsonConverter`] is convenient
179233
if you want to use the same conversion logic on many fields. It also allows
180234
you to support a type within collections. Check out
181235
[these examples](https://github.com/google/json_serializable.dart/blob/master/example/lib/json_converter_example.dart).
182236
237+
```dart
238+
@JsonSerializable()
239+
class Sample4 {
240+
Sample4(this.value);
241+
242+
factory Sample4.fromJson(Map<String, dynamic> json) =>
243+
_$Sample4FromJson(json);
244+
245+
@EpochDateTimeConverter()
246+
final DateTime value;
247+
248+
Map<String, dynamic> toJson() => _$Sample4ToJson(this);
249+
}
250+
251+
class EpochDateTimeConverter implements JsonConverter<DateTime, int> {
252+
const EpochDateTimeConverter();
253+
254+
@override
255+
DateTime fromJson(int json) => DateTime.fromMillisecondsSinceEpoch(json);
256+
257+
@override
258+
int toJson(DateTime object) => object.millisecondsSinceEpoch;
259+
}
260+
```
261+
183262
# Build configuration
184263
185264
Aside from setting arguments on the associated annotation classes, you can also

json_serializable/build.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ targets:
1818
- test/kitchen_sink/*
1919
- test/literal/*
2020
- test/supported_types/*
21+
- tool/readme/*
2122

2223
json_serializable|_test_builder:
2324
generate_for:

json_serializable/tool/readme/enum_example.dart

Lines changed: 0 additions & 25 deletions
This file was deleted.
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
import 'package:json_annotation/json_annotation.dart';
2+
3+
part 'readme_examples.g.dart';
4+
5+
// # simple_example
6+
enum StatusCode {
7+
@JsonValue(200)
8+
success,
9+
@JsonValue(301)
10+
movedPermanently,
11+
@JsonValue(302)
12+
found,
13+
@JsonValue(500)
14+
internalServerError,
15+
}
16+
17+
// # enhanced_example
18+
@JsonEnum(valueField: 'code')
19+
enum StatusCodeEnhanced {
20+
success(200),
21+
movedPermanently(301),
22+
found(302),
23+
internalServerError(500);
24+
25+
const StatusCodeEnhanced(this.code);
26+
final int code;
27+
}
28+
29+
// # to_from
30+
@JsonSerializable()
31+
class Sample1 {
32+
Sample1(this.value);
33+
34+
factory Sample1.fromJson(Map<String, dynamic> json) =>
35+
_$Sample1FromJson(json);
36+
37+
// Sample2 is NOT annotated with @JsonSerializable(), but that's okay
38+
// The class has a `fromJson` constructor and a `toJson` method, which is
39+
// all that is required.
40+
final Sample2 value;
41+
42+
Map<String, dynamic> toJson() => _$Sample1ToJson(this);
43+
}
44+
45+
class Sample2 {
46+
Sample2(this.value);
47+
48+
// The convention is for `fromJson` to take a single parameter of type
49+
// `Map<String, dynamic>` but any JSON-compatible type is allowed.
50+
factory Sample2.fromJson(int value) => Sample2(value);
51+
final int value;
52+
53+
// The convention is for `toJson` to take return a type of
54+
// `Map<String, dynamic>` but any JSON-compatible type is allowed.
55+
int toJson() => value;
56+
}
57+
58+
// # json_key
59+
@JsonSerializable()
60+
class Sample3 {
61+
Sample3(this.value);
62+
63+
factory Sample3.fromJson(Map<String, dynamic> json) =>
64+
_$Sample3FromJson(json);
65+
66+
@JsonKey(
67+
toJson: _toJson,
68+
fromJson: _fromJson,
69+
)
70+
final DateTime value;
71+
72+
Map<String, dynamic> toJson() => _$Sample3ToJson(this);
73+
74+
static int _toJson(DateTime value) => value.millisecondsSinceEpoch;
75+
static DateTime _fromJson(int value) =>
76+
DateTime.fromMillisecondsSinceEpoch(value);
77+
}
78+
79+
// # json_converter
80+
@JsonSerializable()
81+
class Sample4 {
82+
Sample4(this.value);
83+
84+
factory Sample4.fromJson(Map<String, dynamic> json) =>
85+
_$Sample4FromJson(json);
86+
87+
@EpochDateTimeConverter()
88+
final DateTime value;
89+
90+
Map<String, dynamic> toJson() => _$Sample4ToJson(this);
91+
}
92+
93+
class EpochDateTimeConverter implements JsonConverter<DateTime, int> {
94+
const EpochDateTimeConverter();
95+
96+
@override
97+
DateTime fromJson(int json) => DateTime.fromMillisecondsSinceEpoch(json);
98+
99+
@override
100+
int toJson(DateTime object) => object.millisecondsSinceEpoch;
101+
}

json_serializable/tool/readme/readme_examples.g.dart

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

json_serializable/tool/readme/readme_template.md

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,14 +75,14 @@ Annotate `enum` types with `ja:JsonEnum` (new in `json_annotation` 4.2.0) to:
7575
Annotate `enum` values with `ja:JsonValue` to specify the encoded value to map
7676
to target `enum` entries. Values can be of type `core:String` or `core:int`.
7777

78-
<!-- REPLACE tool/readme/enum_example.dart-simple_example -->
78+
<!-- REPLACE tool/readme/readme_examples.dart-simple_example -->
7979

8080
If you are annotating an
8181
[enhanced enum](https://dart.dev/guides/language/language-tour#declaring-enhanced-enums),
8282
you can use `ja:JsonEnum.valueField` to specify the field to use for the
8383
serialized value.
8484

85-
<!-- REPLACE tool/readme/enum_example.dart-enhanced_example -->
85+
<!-- REPLACE tool/readme/readme_examples.dart-enhanced_example -->
8686

8787
# Supported types
8888

@@ -107,15 +107,23 @@ customize the encoding/decoding of any type, you have a few options.
107107
`toJson()` function to the type. Note: while you can use `json_serializable`
108108
for these types, you don't have to! The generator code only looks for these
109109
methods. It doesn't care how they were created.
110+
111+
<!-- REPLACE tool/readme/readme_examples.dart-to_from -->
112+
110113
1. Use the `ja:JsonKey.toJson` and `ja:JsonKey.fromJson` properties to specify
111114
custom conversions on the annotated field. The functions specified must be
112115
top-level or static. See the documentation of these properties for details.
116+
117+
<!-- REPLACE tool/readme/readme_examples.dart-json_key -->
118+
113119
1. Create an implementation of `ja:JsonConverter` and annotate either the
114120
corresponding field or the containing class. `ja:JsonConverter` is convenient
115121
if you want to use the same conversion logic on many fields. It also allows
116122
you to support a type within collections. Check out
117123
[these examples](https://github.com/google/json_serializable.dart/blob/master/example/lib/json_converter_example.dart).
118124

125+
<!-- REPLACE tool/readme/readme_examples.dart-json_converter -->
126+
119127
# Build configuration
120128

121129
Aside from setting arguments on the associated annotation classes, you can also

json_serializable/tool/readme_builder.dart

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ class _ReadmeBuilder extends Builder {
2424
final replacements = {
2525
...await buildStep.getExampleContent('example/example.dart'),
2626
...await buildStep.getExampleContent('example/example.g.dart'),
27-
...await buildStep.getExampleContent('tool/readme/enum_example.dart'),
27+
...await buildStep.getExampleContent('tool/readme/readme_examples.dart'),
2828
'supported_types': _classCleanAndSort(supportedTypes()),
2929
'collection_types': _classCleanAndSort(collectionTypes()),
3030
'map_key_types': _classCleanAndSort(mapKeyTypes),
@@ -44,11 +44,14 @@ class _ReadmeBuilder extends Builder {
4444
final foundClasses = SplayTreeMap<String, String>(compareAsciiLowerCase);
4545

4646
final theMap = <Pattern, String Function(Match)>{
47-
RegExp(r'<!-- REPLACE ([\/\w\d\._-]+) -->'): (match) {
48-
final replacementKey = match.group(1)!;
47+
RegExp(r'( *)<!-- REPLACE ([\/\w\d\._-]+) -->'): (match) {
48+
final replacementKey = match.group(2)!;
4949
availableKeys.remove(replacementKey);
50-
return (replacements[replacementKey] ?? '*MISSING! `$replacementKey`*')
51-
.trim();
50+
final replacement =
51+
(replacements[replacementKey] ?? '*MISSING! `$replacementKey`*')
52+
.trim();
53+
54+
return replacement.indent(match.group(1)!);
5255
},
5356
RegExp(r'`(\w+):(\w+)(\.\w+)?`'): (match) {
5457
final context = match.group(1)!;
@@ -278,4 +281,7 @@ ${trim()}
278281
```''';
279282

280283
static const _blockComment = r'// # ';
284+
285+
String indent(String indent) =>
286+
LineSplitter.split(this).map((e) => '$indent$e'.trimRight()).join('\n');
281287
}

0 commit comments

Comments
 (0)