JSON with Unity

Most data returned by Facebook APIs will be in the form of JSON strings. To help you work with them quickly, we've included the widely-used MiniJson as part of our distribution; see its documentation for further details. The most important method from that class, for present purposes, is Deserialize(). To use it, you will have to import the implementation of MiniJSON included in the Facebook namespace: using Facebook.MiniJSON;.

Deserialize

Creates a dictionary from a JSON string representation.

public static object Deserialize(
    string json
)

Name Type Description

json

string

The string has to be a legal JSON object. In the simplest case, a JSON object is an atomic value, which must be of an allowed type (int, float, string, or bool). Strings are surrounded by double quotes; the rest are bare literals. A JSON object may also be an array of JSON objects, where the elements are enclosed in square brackets ([]) and separated by commas. Finally, a JSON object may be a dictionary of string-valued keys to JSON object values, where the dictionary is enclosed in curly brackets ({}), each key is followed by a colon and then its value, and key/value pairs are separated by a comma.

To use Deserialize, specify the type of object you expect to get from it, as in the example below.

Example

// Suppose you have a string jsonString whose value is:
// {"name": "Jason Stringe", "user_id": "75782347",
//  "friends": 
//   {"data": [{"first_name": "Sally", "user_id": "98198298"}]}
// }

//Notice that we're using the Facebook implementation of MiniJSON:
using Facebook.MiniJSON;
... 

var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
string userName = dict["name"];

object friendsH;
var friends = new List<object>();
string friendName;
if(dict.TryGetValue ("friends", out friendsH)) {
  friends = (List<object>)(((Dictionary<string, object>)friendsH) ["data"]);
  if(friends.Count > 0) {
    var friendDict = ((Dictionary<string,object>)(friends[0]));
    var friend = new Dictionary<string, string>();
    friend["id"] = (string)friendDict["id"];
    friend["first_name"] = (string)friendDict["first_name"];
  }
}