dart-json-mapper icon indicating copy to clipboard operation
dart-json-mapper copied to clipboard

Bug: `@JsonProperty(flatten: true)` fails on deserialization

Open KernelPanic92 opened this issue 7 months ago • 0 comments

When using the @JsonProperty(flatten: true) flag, the library correctly serializes the object into a flat JSON structure. However, deserialization fails with a null named arguments error.

Example

Model classes

@jsonSerializable
class MyObject {
  @JsonProperty(name: 'name')
  final String name;
  
  @JsonProperty(flatten: true)
  final FlattenObject page;

  MyObject({
    required this.name,
    required this.page,
  });
}

@jsonSerializable
class FlattenObject {
  @JsonProperty(name: 'pageNumber')
  final int pageNumber;
  
  @JsonProperty(name: 'pageSize')
  final int pageSize;

  FlattenObject({
    required this.pageNumber,
    required this.pageSize,
  });
}

Tests

test('can deserialize', () {
  const json = """
    {
      "name": "Lost Mine of Phandelver",
      "pageNumber": 1,
      "pageSize": 10
    }
  """;

  final actual = JsonMapper.deserialize<MyObject>(jsonDecode(json));
  expect(actual, isA<MyObject>());
});

test('can serialize', () {
  const expected = """{
 "name": "Lost Mine of Phandelver",
 "pageNumber": 1,
 "pageSize": 10
}""";

  final prova = MyObject(
    name: 'Lost Mine of Phandelver',
    page: FlattenObject(pageNumber: 1, pageSize: 10),
  );

  final actual = JsonMapper.serialize(prova);

  expect(actual, expected);
});

Behavior

  • can serialize — passes as expected.
  • can deserialize — fails with the following error:
Unable to instantiate class 'MyObject'
  with null named arguments [Symbol("page")]
package:dart_json_mapper/src/mapper.dart 988:7  JsonMapper._deserializeObject
package:dart_json_mapper/src/mapper.dart 53:21  JsonMapper.deserialize

Expected

The deserialization should populate the FlattenObject from the flattened JSON fields (pageNumber, pageSize), matching the behavior of serialization.

Additional Info

  • Flutter SDK version: 3.29.2
  • dart-json-mapper version: 2.2.14

KernelPanic92 avatar Apr 23 '25 22:04 KernelPanic92