|
1 | 1 | import 'dart:convert';
|
2 | 2 |
|
3 | 3 | import 'package:github/src/common/util/utils.dart';
|
4 |
| -import 'package:github/src/util.dart'; |
5 | 4 |
|
| 5 | +/// Internal class for Json encoding |
| 6 | +/// that should be used instead of `dart:convert`. |
| 7 | +/// |
| 8 | +/// It contains methods that ensures that converted Json |
| 9 | +/// will work with the GitHub API. |
6 | 10 | class GitHubJson {
|
7 |
| - GitHubJson._(); |
| 11 | + const GitHubJson._(); |
8 | 12 |
|
| 13 | + /// Called only if an object is of a non primitive type. |
| 14 | + /// |
| 15 | + /// If [object] is a [DateTime], it converts it to a String whose format is compatible with the API. |
| 16 | + /// Else, it uses the default behavior of [JsonEncoder] which is to call `toJson` method onto [object]. |
| 17 | + /// |
| 18 | + /// If [object] is not a [DateTime] and don't have a `toJson` method, an exception will be thrown |
| 19 | + /// but handled by [JsonEncoder]. |
| 20 | + /// Do not catch it. |
9 | 21 | static dynamic _toEncodable(dynamic object) {
|
10 | 22 | if (object is DateTime) {
|
11 | 23 | return dateToGitHubIso8601(object);
|
12 | 24 | }
|
| 25 | + // `toJson` could return a [Map] or a [List], |
| 26 | + // so we have to delete null values in them. |
13 | 27 | return _checkObject(object.toJson());
|
14 | 28 | }
|
15 | 29 |
|
| 30 | + /// Encodes [object] to a Json String compatible with the GitHub API. |
| 31 | + /// It should be used instead of `jsonEncode`. |
| 32 | + /// |
| 33 | + /// Equivalent to `jsonEncode` except that |
| 34 | + /// it converts [DateTime] to a proper String for the GitHub API, |
| 35 | + /// and it also deletes keys associated with null values in maps before converting them. |
| 36 | + /// |
| 37 | + /// The obtained String can be decoded using `jsonDecode`. |
16 | 38 | static String encode(Object object, {String indent}) {
|
17 | 39 | final encoder = JsonEncoder.withIndent(indent, _toEncodable);
|
18 | 40 | return encoder.convert(_checkObject(object));
|
19 | 41 | }
|
20 | 42 |
|
| 43 | + /// Deletes keys associated with null values |
| 44 | + /// in every map contained in [object]. |
21 | 45 | static dynamic _checkObject(dynamic object) {
|
22 | 46 | if (object is Map) {
|
23 | 47 | return createNonNullMap(object, recursive: true);
|
|
0 commit comments