Hello out there!
I’m working on coding an in-game message system for a Facebook game and am having some difficulties wrapping my head around deserializing the JSON information I’m getting back. The example code provided by Facebook seemed like a good jumping off point, but I must be going wrong somewhere because I’m getting an error stating that I “cannot cast from source type to destination type”. I’ve been up for about a day and a half now, so I may just be missing something incredibly obvious, but since I’m new to handling JSON at all, I thought I’d ask. (If you’ve got links to any good tutorials, I’d love to see them!)
Here’s an example of the JSON info:
{
"data": [
{
"application": {
"category": "Games",
"link": "https:\/\/www.facebook.com\/game-name-here\/",
"name": "Example Game",
"namespace": "example-game",
"id": "000000000000000"
},
"created_time": "2015-08-17T14:49:28+0000",
"from": {
"name": "Player One",
"id": "1111111111111111"
},
"message": "Player One sent you a life!",
"to": {
"name": "Player Two",
"id": "22222222222222222"
},
"id": "333333333333333_44444444444444444"
}
]
}
And here’s my deserializition code, extracted from the full script for example purposes:
using Facebook;
using Facebook.MiniJSON;
public class FBManager : MonoBehaviour
{
public void CheckMessages(FBResult result)
{
if(result.Error != null)
{
Debug.LogError("Error retrieving messages from Facebook.");
}
else
{
Debug.LogError("Checking messages: " + result.Text);
var responseObject = Json.Deserialize(result.Text) as Dictionary<string, object>;
object messagesH;
var messages = new List<object>();
if (responseObject.TryGetValue("data", out messagesH))
{
messages = (List<object>)(((Dictionary<string, object>)messagesH)["data"]);
if(messages.Count > 0)
{
var msgDict = ((Dictionary<string,object>)(messages[0]));
var msg = new Dictionary<string, string>();
msg["from"] = (string)msgDict["from"];
msg["message"] = (string)msgDict["message"];
Debug.LogError("Message from " + msg["from"] + ": " + msg["message"]);
}
}
}
}
}
The “cannot cast” error seems to be coming from this line:
messages = (List<object>)(((Dictionary<string, object>)messagesH)["data"]);
For reference, here’s a link to the Facebook example:
I’ll keep poking and prodding at it, but would certainly appreciate any pointers & assistance. Thanks!