0

I am currently using facebook and I have a callback method that returns a JSON result as a string.

The result has the following format:

{
"request": "420211088059698",
"to": [
    "100002669403922",
    "100000048490273"
]
}

How would I go about parsing the "to" into a list of some sort? This way I can use this list to verify that the user actually did indeed send a request to a friend to play the game.

Thanks guys

3 Answers3

0

You need to convert it to a class array. That can be done with Unity's built in JsonUtility API.

JsonUtility.ToJson to convert a class to Json.

JsonUtility.FromJson to convert Json back to class.

Visit here Json array example.

EDIT:

You asked for an example:

class FacebookInfo
{
    public string request;
    public string[] to;
}

void Start()
{
    FacebookInfo fbInfo = new FacebookInfo();
    string fbJson = "{\"request\": \"420211088059698\",\"to\": [\"100002669403922\",\"100000048490273\"]}";
    fbInfo = JsonUtility.FromJson<FacebookInfo>(fbJson);

    //Show request
    Debug.Log("Request: " + fbInfo.request);

    //Show to arrays
    for (int i = 0; i < fbInfo.to.Length; i++)
    {
        Debug.Log("To : " + fbInfo.to[i]);
    }
}

Tested with Unity 5.4.0.13B and it looks like Unity now support Json array without writing extra code. Just make sure you have this version I mentioned.

Community
  • 1
  • 1
Programmer
  • 121,791
  • 22
  • 236
  • 328
  • My JSON data seems less complex than the example provided. So how would I go about parsing that data? – coder_4_life25 May 23 '16 at 05:55
  • 1
    @coder_4_life25 Gave an example. It's not. Using **Unity 5.4.0.13B** and it worked. I think that Unity updated their API so that you don't need to go that extra mile. You don't need external libraries like you do before and should avoid using one because the built in version is about 10x faster than external ones. This statement is based on my tests. – Programmer May 23 '16 at 06:07
  • 1
    @Programmer yes I second that the internal JSON parser is very fast – LumbusterTick May 23 '16 at 07:21
0

You can use JSON.Net for deserializing to a class of below structure:

Class Test{
public string request {get;set;}
public List<string> to {get;set;}
}

then just call deserialize method on the JSON string to get the object.

Test obj = JsonConvert.DeserializeObject<Test>(jsonstring);
shbht_twr
  • 505
  • 3
  • 14
0

just use SimpleJson http://wiki.unity3d.com/index.php/SimpleJSON , no extra work needed , look at the example , all you need to do is use JSON.Parse and you an array and can use it like data["request"] to get the values, hope this helps.

LumbusterTick
  • 1,067
  • 10
  • 21