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

Transforming empty nested map to object exception #1388

Open
burekas7 opened this issue Jan 7, 2024 · 1 comment
Open

Transforming empty nested map to object exception #1388

burekas7 opened this issue Jan 7, 2024 · 1 comment

Comments

@burekas7
Copy link

burekas7 commented Jan 7, 2024

Following to this issue:
https://stackoverflow.com/questions/75522984/transforming-empty-nested-map-to-object-exception

I have the same problem.
But this problem happens only when I run a unit tests.
When I use the parse the same json in my app (Get the same json as dio response) it's ok,
But when I use the same json as mock value for unit tests, it throws an exception since there is object value {}

What is the best way to handle cases of empty objects?
Why does it happen only in the unit tests when I use the json object as mock value.

(When e value is {}, not null)

Location.fromJson(e as Map<String, dynamic>))

It comes from this:
(When json['locations'] value is [{}], not null)
From the generated file.
The problem is with the Location.fromJson

      locations: (json['locations'] as List<dynamic>?)
          ?.map((e) => Location.fromJson(e as Map<String, dynamic>))
          .toList(),

The main problem is with e as Map<String, dynamic> that behaves differently.

Unhandled exception:
type '_Map<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>' in type cast

Thank you in advance.

@burekas7
Copy link
Author

burekas7 commented Jan 7, 2024

I see there is a manual solution like this:
But how can I set this option for all my models using JsonSerializable, instead of doing it one by one?

import 'package:json_annotation/json_annotation.dart';

part 'my_data.g.dart';

@JsonSerializable()
class MyData {
  @JsonKey(fromJson: _fromJson, toJson: _toJson)
  Map<String, dynamic>? key;

  MyData({this.key});

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

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

  static Map<String, dynamic>? _fromJson(Map<String, dynamic>? json) {
    // Check if json is an empty object and return null
    return json != null && json.isEmpty ? null : json;
  }

  static Map<String, dynamic>? _toJson(Map<String, dynamic>? json) {
    // Check if json is an empty object and return null
    return json != null && json.isEmpty ? null : json;
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant