2021年2月6日星期六

JsonSerializable - fromJson throwing _InternalLinkedHashMap

I have used this build.yaml config to allow nested objects to be parsed to json:

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

It definitely seems to have worked as the toJson with nested objects works fine. Then I'm trying to create a class instance from json with https://pub.dev/packages/json_serializable:

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

I'm getting this exception:

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

This is the value of json:

enter image description here

The red covered values are strings. When the user_credential_entity.password and user_credential_entity.emailAddress are null, there is no error.

I think it's because user_credential_entity is a nested JsonSerializable object. However toJson works, but fromJson doesn't.

the parent class:

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);  

the child class:

@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);  

The actual line of code the error is on is here:

enter image description here

Is the value of json['userCredentialEntity'] not a Map<String, dynamic>? Kinda looks like one to me.

https://stackoverflow.com/questions/66082343/jsonserializable-fromjson-throwing-internallinkedhashmapdynamic-dynamic-ex February 07, 2021 at 05:50AM

没有评论:

发表评论