Convert all the keys and values of a Map to String in Dart

2,986

Currently there is a pull request for allowing field names. https://github.com/dart-lang/protobuf/pull/83

Share:
2,986
M20
Author by

M20

I like to learn.

Updated on December 07, 2022

Comments

  • M20
    M20 over 1 year

    The problem I am having is related to serialization and decoding JSON. I am trying to serialize a Protobuf message to use it with redux persist.

    This is the method I call to serialize my object:

      Map<String, dynamic> toJSON(){
    
        return <String, dynamic>{
            'isLogged': this.isLogged,
            'isExpired': this.isExpired,
            'protoUser':
                this.protoUser == null ? null : this.protoUser.writeToJsonMap()),
            'error': this.error,
          }
      };
    

    and this is the method I use to read the persisted state:

      factory AuthState.fromJSON(Map<String, dynamic> json){
        new AuthState(
          isLogged: json['isLogged'],
          isExpired: json['isExpired'],
          error: json['error'],
          protoUser: json['protoUser'] == null
              ? null
              : new Auth.fromJson(json['protoUser'].toString()),
        );
      }
    

    The problem I have is that writeToJsonMap do not write a valid JSON map for dart. So when reading the serialized state, I get this error:

    E/flutter (24643): FormatException: Unexpected character (at character 2)
    E/flutter (24643): {1: 200, 2: test1, 3: test2, 4: {1: 1, 3: Mike, 4: tester}}
    

    also asked on https://github.com/dart-lang/protobuf/issues/136