Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example updates - 2 commits #350

Merged
merged 3 commits into from Oct 20, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 8 additions & 7 deletions .travis.yml
@@ -1,4 +1,4 @@
# Created with package:mono_repo v1.2.0
# Created with package:mono_repo v1.2.1
language: dart

# Custom configuration
Expand All @@ -13,13 +13,13 @@ branches:
jobs:
include:
- stage: analyzer_and_format
name: "SDK: stable - DIR: example - TASKS: dartfmt -n --set-exit-if-changed ."
script: ./tool/travis.sh dartfmt
name: "SDK: dev - DIR: example - TASKS: [dartfmt -n --set-exit-if-changed ., dartanalyzer --fatal-infos --fatal-warnings .]"
script: ./tool/travis.sh dartfmt dartanalyzer_0
env: PKG="example"
dart: stable
- stage: analyzer_and_format
name: "SDK: stable - DIR: example - TASKS: dartanalyzer --fatal-infos --fatal-warnings ."
script: ./tool/travis.sh dartanalyzer_0
dart: dev
- stage: analyzer_and_format_stable
name: "SDK: stable - DIR: example - TASKS: [dartfmt -n --set-exit-if-changed ., dartanalyzer --fatal-warnings .]"
script: ./tool/travis.sh dartfmt dartanalyzer_1
env: PKG="example"
dart: stable
- stage: unit_test
Expand Down Expand Up @@ -71,4 +71,5 @@ stages:
cache:
directories:
- "$HOME/.pub-cache"
- example/.dart_tool/build
- json_serializable/.dart_tool/build
6 changes: 3 additions & 3 deletions example/README.md
Expand Up @@ -8,11 +8,11 @@ dependencies to your `pubspec.yaml`.

```yaml
dependencies:
json_annotation: ^1.0.0
json_annotation: ^1.2.0

dev_dependencies:
build_runner: ^0.10.0
json_serializable: ^1.0.0
build_runner: ^1.0.0
json_serializable: ^1.5.1
```

Annotate your code with classes defined in
Expand Down
21 changes: 13 additions & 8 deletions example/lib/example.dart
Expand Up @@ -3,6 +3,7 @@
// BSD-style license that can be found in the LICENSE file.

import 'package:json_annotation/json_annotation.dart';

part 'example.g.dart';

@JsonSerializable()
Expand Down Expand Up @@ -39,7 +40,7 @@ class Order {

@JsonKey(
name: 'prep-time',
fromJson: _durationFromMillseconds,
fromJson: _durationFromMilliseconds,
toJson: _durationToMilliseconds)
Duration prepTime;

Expand All @@ -51,15 +52,19 @@ class Order {
factory Order.fromJson(Map<String, dynamic> json) => _$OrderFromJson(json);

Map<String, dynamic> toJson() => _$OrderToJson(this);
}

Duration _durationFromMillseconds(int milliseconds) =>
Duration(milliseconds: milliseconds);
int _durationToMilliseconds(Duration duration) => duration.inMilliseconds;
static Duration _durationFromMilliseconds(int milliseconds) =>
Duration(milliseconds: milliseconds);

static int _durationToMilliseconds(Duration duration) =>
duration.inMilliseconds;

DateTime _dateTimeFromEpochUs(int us) =>
DateTime.fromMicrosecondsSinceEpoch(us);
int _dateTimeToEpochUs(DateTime dateTime) => dateTime.microsecondsSinceEpoch;
static DateTime _dateTimeFromEpochUs(int us) =>
DateTime.fromMicrosecondsSinceEpoch(us);

static int _dateTimeToEpochUs(DateTime dateTime) =>
dateTime.microsecondsSinceEpoch;
}

@JsonSerializable()
class Item {
Expand Down
13 changes: 7 additions & 6 deletions example/lib/example.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

76 changes: 76 additions & 0 deletions example/lib/json_converter_example.dart
@@ -0,0 +1,76 @@
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:json_annotation/json_annotation.dart';

part 'json_converter_example.g.dart';

@JsonSerializable()
class GenericCollection<T> {
@JsonKey(name: 'page')
final int page;

@JsonKey(name: 'total_results')
final int totalResults;

@JsonKey(name: 'total_pages')
final int totalPages;

@JsonKey(name: 'results')
@_Converter()
final List<T> results;

GenericCollection(
{this.page, this.totalResults, this.totalPages, this.results});

factory GenericCollection.fromJson(Map<String, dynamic> json) =>
_$GenericCollectionFromJson<T>(json);

Map<String, dynamic> toJson() => _$GenericCollectionToJson(this);
}

class _Converter<T> implements JsonConverter<T, Object> {
const _Converter();

@override
T fromJson(Object json) {
if (json is Map<String, dynamic> &&
json.containsKey('name') &&
json.containsKey('size')) {
return CustomResult.fromJson(json) as T;
}
// This will only work if `json` is a native JSON type:
// num, String, bool, null, etc
// *and* is assignable to `T`.
return json as T;
}

@override
Object toJson(T object) {
// This will only work if `object` is a native JSON type:
// num, String, bool, null, etc
// Or if it has a `toJson()` function`.
return object;
}
}

@JsonSerializable()
class CustomResult {
final String name;
final int size;

CustomResult(this.name, this.size);

factory CustomResult.fromJson(Map<String, dynamic> json) =>
_$CustomResultFromJson(json);

Map<String, dynamic> toJson() => _$CustomResultToJson(this);

@override
bool operator ==(Object other) =>
other is CustomResult && other.name == name && other.size == size;

@override
int get hashCode => name.hashCode * 31 ^ size.hashCode;
}
32 changes: 32 additions & 0 deletions example/lib/json_converter_example.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 13 additions & 2 deletions example/mono_pkg.yaml
Expand Up @@ -4,8 +4,19 @@ dart:

stages:
- analyzer_and_format:
- dartfmt
- dartanalyzer: --fatal-infos --fatal-warnings .
- group:
- dartfmt
- dartanalyzer: --fatal-infos --fatal-warnings .
dart: [dev]
- analyzer_and_format_stable:
- group:
- dartfmt
- dartanalyzer: --fatal-warnings .
dart: [stable]
- unit_test:
# Run the tests -- include the default-skipped presubmit tests
- test: --run-skipped

cache:
directories:
- .dart_tool/build
8 changes: 4 additions & 4 deletions example/pubspec.yaml
Expand Up @@ -2,14 +2,14 @@ name: example
author: Dart Team <misc@dartlang.org>

environment:
sdk: '>=2.0.0-dev.54 <3.0.0'
sdk: '>=2.0.0 <3.0.0'

dependencies:
json_annotation: ^1.0.0
json_annotation: ^1.2.0

dev_dependencies:
build_runner: ^0.10.0
json_serializable: ^1.0.0
build_runner: ^1.0.0
json_serializable: ^1.5.1

# Used by tests. Not required to use `json_serializable`.
build_verify: ^1.0.0
Expand Down
87 changes: 87 additions & 0 deletions example/test/json_convert_example_test.dart
@@ -0,0 +1,87 @@
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:convert';

import 'package:example/json_converter_example.dart';
import 'package:test/test.dart';

void main() {
test('trivial case', () {
var collection = GenericCollection<int>(
page: 0, totalPages: 3, totalResults: 10, results: [1, 2, 3]);

var encoded = _encode(collection);
var collection2 = GenericCollection<int>.fromJson(
jsonDecode(encoded) as Map<String, dynamic>);

expect(collection2.results, [1, 2, 3]);

expect(_encode(collection2), encoded);
});

test('custom result', () {
var collection = GenericCollection<CustomResult>(
page: 0,
totalPages: 3,
totalResults: 10,
results: [CustomResult('bob', 42)]);

var encoded = _encode(collection);
var collection2 = GenericCollection<CustomResult>.fromJson(
jsonDecode(encoded) as Map<String, dynamic>);

expect(collection2.results, [CustomResult('bob', 42)]);

expect(_encode(collection2), encoded);
});

test('mixed values in generic collection', () {
var collection =
GenericCollection(page: 0, totalPages: 3, totalResults: 10, results: [
1,
3.14,
null,
'bob',
['list'],
{'map': 'map'},
CustomResult('bob', 42)
]);

var encoded = _encode(collection);

expect(
() => GenericCollection<CustomResult>.fromJson(
jsonDecode(encoded) as Map<String, dynamic>),
_throwsCastSomething);
expect(
() => GenericCollection<int>.fromJson(
jsonDecode(encoded) as Map<String, dynamic>),
_throwsCastSomething);
expect(
() => GenericCollection<String>.fromJson(
jsonDecode(encoded) as Map<String, dynamic>),
_throwsCastSomething);

var collection2 =
GenericCollection.fromJson(jsonDecode(encoded) as Map<String, dynamic>);

expect(collection2.results, [
1,
3.14,
null,
'bob',
['list'],
{'map': 'map'},
CustomResult('bob', 42)
]);

expect(_encode(collection2), encoded);
});
}

final _throwsCastSomething = throwsA(const TypeMatcher<CastError>());

String _encode(Object object) =>
const JsonEncoder.withIndent(' ').convert(object);
6 changes: 3 additions & 3 deletions example/test/readme_test.dart
Expand Up @@ -20,9 +20,9 @@ void _expect(String fileName) {

final _pubspecContent = r'''
dependencies:
json_annotation: ^1.0.0
json_annotation: ^1.2.0

dev_dependencies:
build_runner: ^0.10.0
json_serializable: ^1.0.0
build_runner: ^1.0.0
json_serializable: ^1.5.1
''';
2 changes: 1 addition & 1 deletion tool/travis.sh
@@ -1,5 +1,5 @@
#!/bin/bash
# Created with package:mono_repo v1.2.0
# Created with package:mono_repo v1.2.1

if [ -z "$PKG" ]; then
echo -e '\033[31mPKG environment variable must be set!\033[0m'
Expand Down