Skip to content

Commit ac08cc2

Browse files
committed
example: Add an example demonstrating how to do nested fields
Closes #490
1 parent 41b5a27 commit ac08cc2

File tree

4 files changed

+93
-0
lines changed

4 files changed

+93
-0
lines changed
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import 'package:json_annotation/json_annotation.dart';
2+
3+
part 'nested_values_example.g.dart';
4+
5+
/// An example work-around for
6+
/// https://github.com/google/json_serializable.dart/issues/490
7+
@JsonSerializable()
8+
class NestedValueExample {
9+
NestedValueExample(this.nestedValues);
10+
11+
factory NestedValueExample.fromJson(Map<String, dynamic> json) =>
12+
_$NestedValueExampleFromJson(json);
13+
14+
@_NestedListConverter()
15+
@JsonKey(name: 'root_items')
16+
final List<String> nestedValues;
17+
18+
Map<String, dynamic> toJson() => _$NestedValueExampleToJson(this);
19+
}
20+
21+
class _NestedListConverter
22+
extends JsonConverter<List<String>, Map<String, dynamic>> {
23+
const _NestedListConverter();
24+
25+
@override
26+
List<String> fromJson(Map<String, dynamic> json) => [
27+
for (var e in json['items'] as List)
28+
(e as Map<String, dynamic>)['name'] as String
29+
];
30+
31+
@override
32+
Map<String, dynamic> toJson(List<String> object) => {
33+
'items': [
34+
for (var item in object) {'name': item}
35+
]
36+
};
37+
}

example/lib/nested_values_example.g.dart

+18
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

example/pubspec.yaml

+3
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ dependencies:
88
json_annotation: ^4.4.0
99

1010
dev_dependencies:
11+
# Used by tests. Not required to use `json_serializable`.
12+
_json_serial_shared_test:
13+
path: ../shared_test
1114
build_runner: ^2.0.0
1215

1316
# Used by tests. Not required to use `json_serializable`.

example/test/nested_values_test.dart

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
2+
// for details. All rights reserved. Use of this source code is governed by a
3+
// BSD-style license that can be found in the LICENSE file.
4+
5+
import 'dart:convert';
6+
7+
import 'package:_json_serial_shared_test/shared_test.dart';
8+
import 'package:example/nested_values_example.dart';
9+
import 'package:test/test.dart';
10+
11+
void main() {
12+
test('NestedValueExample', () {
13+
final input = jsonDecode(_input) as Map<String, dynamic>;
14+
final normalizedOutput = loudEncode(input);
15+
16+
final instance = NestedValueExample.fromJson(input);
17+
18+
expect(loudEncode(instance), normalizedOutput);
19+
});
20+
}
21+
22+
const _input = r'''
23+
{
24+
"root_items": {
25+
"items": [
26+
{
27+
"name": "first nested item"
28+
},
29+
{
30+
"name": "second nested item"
31+
}
32+
]
33+
}
34+
}
35+
''';

0 commit comments

Comments
 (0)