【问题标题】:Convert all the keys and values of a Map to String in Dart在 Dart 中将 Map 的所有键和值转换为字符串
【发布时间】:2019-03-30 06:24:10
【问题描述】:

我遇到的问题与序列化和解码 JSON 有关。我正在尝试序列化 Protobuf 消息以将其与 redux persist 一起使用。

这是我用来序列化我的对象的方法:

  Map<String, dynamic> toJSON(){

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

这是我用来读取持久状态的方法:

  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()),
    );
  }

我遇到的问题是 writeToJsonMap 没有为 dart 编写有效的 JSON 映射。所以在读取序列化状态时,我得到这个错误:

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}}

也在https://github.com/dart-lang/protobuf/issues/136上提问

【问题讨论】:

  • “那么读取序列化状态时”是什么意思?
  • redux persist 是用于保存包含应用程序状态的 redux store 的包。我的意思是在读取序列化文件时。
  • 您做错了什么,但可能是您的问题中未包含的代码中的某些内容。
  • 它类似于github.com/FranPitri/flutter_redux_boilerplate ...唯一的区别是我没有使用用户模型,而是使用了一个protobuf对象。
  • 如果我删除 protoUser 一切正常(json 编码/解码错误)

标签: json dictionary dart flutter


【解决方案1】:

目前有一个允许字段名称的拉取请求。 https://github.com/dart-lang/protobuf/pull/83

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 2021-09-19
    • 1970-01-01
    相关资源
    最近更新 更多