Skip to content

Commit

Permalink
generic fromJson
Browse files Browse the repository at this point in the history
fixes #32
  • Loading branch information
rrousselGit committed Feb 13, 2020
1 parent b12bcc2 commit bf15d28
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# 0.2.5

Fixed a bug where generic json deserialization didn't apply generic parameters (https://github.com/rrousselGit/freezed/issues/32)

# 0.2.4

Make the generated interface a mixin to fix `prefer_mixin` lints (https://github.com/rrousselGit/freezed/issues/28)
Expand Down
2 changes: 1 addition & 1 deletion lib/src/templates/concrete_template.dart
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ $copyWithPrototype

String get redirectedFromJsonConstructor {
if (!shouldGenerateJson) return '';
return 'factory ${constructor.redirectedName}.fromJson(Map<String, dynamic> json) = $concreteName.fromJson;';
return 'factory ${constructor.redirectedName}.fromJson(Map<String, dynamic> json) = $concreteName$genericsParameter.fromJson;';
}

String get concreteFromJsonConstructor {
Expand Down
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: freezed
description: >
Code generation for immutable classes that has a simple syntax/API without
compromising on the features.
version: 0.2.4
version: 0.2.5
homepage: https://github.com/rrousselGit/freezed
authors:
- Remi Rousselet <darky12s@gmail.com>
Expand Down
21 changes: 21 additions & 0 deletions test/integration/json.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,24 @@ abstract class Decorator with _$Decorator {

factory Decorator.fromJson(Map<String, dynamic> json) => _$DecoratorFromJson(json);
}

@immutable
abstract class Generic<T> with _$Generic<T> {
factory Generic(@DataConverter() T a) = _Generic<T>;

factory Generic.fromJson(Map<String, dynamic> json) => _$GenericFromJson<T>(json);
}

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

@override
T fromJson(Object json) {
return json as T;
}

@override
Object toJson(T object) {
return object;
}
}
6 changes: 6 additions & 0 deletions test/json_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ import 'common.dart';
import 'integration/json.dart';

Future<void> main() async {
test('generic json', () {
expect(
Generic<int>.fromJson(<String, dynamic>{'a': 42}),
Generic(42),
);
});
test('single ctor + json can access properties/copyWith', () {
final value = Single(42);

Expand Down

0 comments on commit bf15d28

Please sign in to comment.