【问题标题】:JsonSerializable - fromJson throwing _InternalLinkedHashMap<dynamic, dynamic> exception on nested objectJsonSerializable - fromJson 在嵌套对象上抛出 _InternalLinkedHashMap<dynamic, dynamic> 异常
【发布时间】:2021-05-10 22:05:57
【问题描述】:

我使用了这个build.yaml 配置来允许将嵌套对象解析为json:

targets:
    $default:
        builders:
            json_serializable:
                options:
                    explicit_to_json: true

它似乎确实像 toJson 与嵌套对象一样工作正常。然后我尝试使用https://pub.dev/packages/json_serializable从json创建一个类实例:

  @override
  UserRegistrationEntity getUserRegistration() {
    final json = Map<String, dynamic>.from(
        localDataSource.get(keyToRead: UserRegistrationFieldNames.self) ??
            <String, dynamic>{});
    return UserRegistrationEntity.fromJson(json); <===== ERROR ON THIS LINE
  }

我遇到了这个异常:

抛出异常:类型 '_InternalLinkedHashMap' 是 不是类型转换中“Map”类型的子类型

这是json的值:

红色覆盖的值是字符串。当user_credential_entity.passworduser_credential_entity.emailAddressnull时,没有错误。

我认为这是因为user_credential_entity 是一个嵌套的 JsonSerializable 对象。但是toJson 有效,但fromJson 无效。

父类:

part 'user_registration_entity.g.dart';



@JsonSerializable()
class UserRegistrationEntity implements IEntity<UserRegistrationEntity> {
  UserRegistrationEntity(
      {this.nickName,
      this.emailAddress,
      this.confirmEmailAddress,
      this.password,
      this.confirmPassword,
      this.userCredentialEntity});

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

  String nickName;
  String emailAddress;
  String confirmEmailAddress;
  String password;
  String confirmPassword;
  UserCredentialEntity userCredentialEntity;

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

子类:

@JsonSerializable()
class UserCredentialEntity implements IEntity<UserCredentialEntity> {
  UserCredentialEntity({this.password, this.emailAddress});

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

  String password;
  String emailAddress;

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

错误所在的实际代码行在这里:

json['userCredentialEntity'] 的值不是Map&lt;String, dynamic&gt; 吗?对我来说有点像。

【问题讨论】:

    标签: flutter dart json-serializable


    【解决方案1】:

    解决方法是把它放在包含嵌套对象的类之上:

    @JsonSerializable(explicitToJson: true, anyMap: true)
    

    anyMap: true 是我的关键。

    或者,可以将其添加到build.yaml

    targets:
        $default:
            builders:
                json_serializable:
                    options:
                        explicit_to_json: true
                        any_map: true
    

    这意味着不再需要@JsonSerializable(explicitToJson: true, anyMap: true)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-12
      • 2020-08-20
      • 2018-09-24
      • 2021-02-11
      • 2020-05-31
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      相关资源
      最近更新 更多