Xamarin forms: How to parse string data from notification in ios platform?

Sreejith Sreenivasan 1,001 Reputation points
2023-05-16T13:47:37.62+00:00
Following is my notification body:

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

I can read the `requestData` like below in ios platform:

    var myData = JsonConvert.DeserializeObject<RequestList>(userInfo[new NSString("requestData")] as NSString);

But when I try to read the `commentMessageType` like below I am getting `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);

I tried another way like below, but I got `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);

What is the exact way to parse a string data from notification? 
Developer technologies .NET Xamarin
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-05-16T15:48:50.42+00:00

    no json deserialize is required:

    var commentType = (userInfo[new NSString("commentMessageType")] as NSString).ToString();
    

    note: the json deserialize fails, because the string quotes are lost when the dictionary value is fetched, thus its no longer valid json. arrays and objects will work.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.