Xamarin Forms iOS平台:如何正确解析通知中的字符串数据?
iOS平台解析FCM通知字符串数据的问题
我的FCM通知体如下:
{ "to" : "My device FCM Token", "notification" : { "body" : "Hi....", "title": "Test" }, "data" : { "commentMessageType": "support", "requestData": { "request": { "itemId": 3462, "itemTitle": "Request for books", "itemDescription": "Request for books", }, "category": "Books", "companyId": 74366, "companyName": "manish thomas-Furniture Mart hub", "location": { "locationId": 0, "locationName": null, "blogCollectionId": 0, "fileUrl": null }, "lockedLocation": null, "itemRequesterName": "Albee " } } }
在iOS平台,我可以通过以下代码成功读取requestData:
var myData = JsonConvert.DeserializeObject<RequestList>(userInfo[new NSString("requestData")] as NSString);
但读取commentMessageType时遇到错误:Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: s. Path '', line 1, position 1.
对应的代码是:
var commentType = JsonConvert.DeserializeObject<String>(userInfo[new NSString("commentMessageType")] as NSString);
换另一种方式尝试时,又出现System.NullReferenceException: Object reference not set to an instance of an object错误:
NSDictionary data = userInfo.ObjectForKey(new NSString("data")) as NSDictionary; string commentType = Convert.ToString(data[new NSString("commentMessageType")] as NSString);
请问iOS平台解析通知中字符串数据的正确方法是什么?
解决方案
错误原因
- 第一个错误:
JsonConvert.DeserializeObject<String>用于解析JSON格式字符串,但commentMessageType本身是普通字符串"support",并非JSON结构(比如带双引号的"support"),直接反序列化会触发格式错误。 - 第二个错误:
userInfo中data的获取方式有误,导致data为null,进而引发空引用异常。
正确解析代码
在iOS的FCM回调中,userInfo里的data是字典类型,普通字符串值无需JSON反序列化,直接提取即可。同时必须添加空值判断避免异常:
// 安全获取data字典 if (userInfo.TryGetValue(new NSString("data"), out NSObject dataObj) && dataObj is NSDictionary dataDict) { // 提取commentMessageType字符串 if (dataDict.TryGetValue(new NSString("commentMessageType"), out NSObject commentObj)) { string commentType = commentObj.ToString(); // 此处使用commentType } }
简洁写法(Xamarin.iOS)
var dataDict = userInfo["data"] as NSDictionary; string commentType = dataDict?["commentMessageType"]?.ToString() ?? string.Empty;
补充说明
requestData是JSON对象,所以需要用JsonConvert.DeserializeObject反序列化为实体类,这和普通字符串类型的commentMessageType处理逻辑不同。- 所有字典操作都要加空值判断,防止FCM通知结构异常导致崩溃。
内容的提问来源于stack exchange,提问作者Sreejith Sree
相关产品推荐
相关产品推荐

