Flutter-使用json_serializable

时间:2019-04-29 14:13:10

标签: json flutter firebase-cloud-messaging

我正在我的应用程序中的所有模型上使用Json_serializable(它通过命令行自动为我的模型提供了fromJson和toJson方法)。

每个(反)序列化都可以正常运行,但不能与firebase_messaging json配合使用。

这是我的工作:

onMessage: (Map<String, dynamic> msg) {
  FCMNotification fcmNotification = FCMNotification.fromJson(msg);
}

我总是有这种错误:

  

类型'String'不是类型转换中类型'Map '的子类型

  

'_ InternalLinkedHashMap <动态,动态>'不是'Map <字符串,动态>'类型的子类型

我已经在github here中看到了这种问题,但是我没有找到任何解决方案。请帮助

1 个答案:

答案 0 :(得分:0)

我找到了问题和解决方案。

Firebase Cloud Messaging通知作为地图接收。

地图的结构类似于:

{
"registration_ids": ["registrationID1, "registrationID2", ...],
"notification": {
  "title": "New message",
  "body": "new message in channel: test"
},
"data": {
  "type": "CHANNEL_MESSAGE",
  "author": {
    "id": 5,
    "firstName": "John",
    "lastName": "Doe",
    "email": "J.doe@email.com",
    "userType": "USER",
    "language": "EN"
  },
}

}

我们可以将所需的内容放入“数据”中。就我而言,我有一个作者对象。 该对象在地图中添加了一个附加级别。 Firebase Cloud Messaging认为所有附加级别的值都是String。

因此,我们可以使用传统的'fromJson(json)'方法对'data'进行反序列化,但是如果要对'author'进行反序列化,则必须先对Json进行解码,如下所示:

String jsonAuthorStr = msg["data"]["author"];
Map<String, dynamic> temp = json.decode(jsonAuthorStr);

然后反序列化:

Author author = Author.fromJson(temp);