Skip to content

Custom types and custom encoding example not working #1489

@apomalyn

Description

@apomalyn

Hello there! 👋

First, thank you for this amazing package!

I wanted to point out that the following example isn't working as expected.

@JsonSerializable()
class Sample1 {
  Sample1(this.value);

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

  // Sample2 is NOT annotated with @JsonSerializable(), but that's okay
  // The class has a `fromJson` constructor and a `toJson` method, which is
  // all that is required.
  final Sample2 value;

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

class Sample2 {
  Sample2(this.value);

  // The convention is for `fromJson` to take a single parameter of type
  // `Map<String, dynamic>` but any JSON-compatible type is allowed.
  factory Sample2.fromJson(int value) => Sample2(value);
  final int value;

  // The convention is for `toJson` to take return a type of
  // `Map<String, dynamic>` but any JSON-compatible type is allowed.
  int toJson() => value;
}

toJson should return:

{ "value": 5 }

but instead returns:

 {'value': Instance of 'Sample2'}
Tests used
void main() {
  group("Sample", () {
    final sample = Sample1(Sample2(5));

    test("toJson", () { // Failing
      expect(sample.toJson(), { 
        "value": 5,
      });
    });

    test("fromJson", () { // Working as expected
      final decoded = Sample1.fromJson({
        "value": 5,
      });

      expect(decoded.value, isA<Sample2>());
      expect(decoded.value.value, 5);
    });
  });
}

I'm probably missing something silly, so sorry if this is the case.

Also, using a converter is possible to fix it but annoying when Sample2 is used in a lot of class.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions