PHP JSON to Unity C# and Vice Versa

So, you have a backend script in PHP that returns JSON string and you want to parse that data from your Unity game. What would you do?
Based on my experience, here is how I do it.

PHP

Let’s say I have a PHP script (index.php) like this:

<?php

$MyData= new stdClass();
$MyData->objects = ["One", "Two", "Three"];

header('Content-Type: application/json; charset=utf-8');
echo json_encode($MyData);

And that php script is placed somewhere on my web server and I can access it from my web browser using this address: http://localhost/myweb/index.php

I can see json text when I open that page. Then, I wan to process that json text inside my Unity game.

Unity

So the next thing is about Unity, here is a script I named it OnlineData.cs and the content is like this:

using System;

[Serializable]

public class OnlineData
{
    public string[] objects;
}

In my Unity editor, I make an empty game object. Then I create another script thus I attach the script to that game object. The script I named it Fetch.cs and here is the content:

using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

public class Fetch : MonoBehaviour
{

    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(ParseData());
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    IEnumerator ParseData() {
        WWWForm form = new WWWForm();
        form.AddField("getlist", "all");
        using (UnityWebRequest www = UnityWebRequest.Post("http://localhost/myweb/index.php", form))
        {
            www.downloadHandler = new DownloadHandlerBuffer();
            yield return www.SendWebRequest();

            if (www.result == UnityWebRequest.Result.ConnectionError)
            {
                Debug.Log(www.error);
            }
            else
            {
                string responseText = www.downloadHandler.text;
                Debug.Log(responseText);

                OnlineData od = new OnlineData();
                od = JsonUtility.FromJson<OnlineData>(responseText);
                foreach (string o in od.objects) {
                    Debug.Log(o);
                }

            }
        }
    }
}

Play it!

Okay, next step is to run it. Hit the play button, and watch the console window. You will see the server’s response there.

What about converting data back to JSON ?

As you’ve seen above, we used JsonUtility.FromJson to parse data from json text. If we want to do the otherwise, we can use JsonUtility.ToJson. Check out official Unity documentation about JSON serialization here.

Leave a Reply

Your email address will not be published. Required fields are marked *