Skip to content

Instantly share code, notes, and snippets.

@gekidoslair
Created October 19, 2014 06:12
Show Gist options
  • Save gekidoslair/dbbe29f37c46ca37d3a1 to your computer and use it in GitHub Desktop.
Save gekidoslair/dbbe29f37c46ca37d3a1 to your computer and use it in GitHub Desktop.
Parsing JSON into C# objects in Unity
public class CommunicationLayer : Monobehavior
{
public string response_message;
string baseAPIEndpoint = ClientConstants.GAMESERVER_URL; // base url for your API endpoints
/// <summary>
/// Sends a Generic API call. should be done via coroutine
/// </summary>
/// <returns>The API call.</returns>
/// <param name="endpoint">Endpoint we are wanting to hit</param>
/// <param name="endpoint">callbackObject - name of the game object that we will notify once the json is loaded.</param>
/// <param name="endpoint">callbackSuccess - function name we're going to call if all goes well.</param>
/// <param name="endpoint">callbackError - function we're going to call if things go south.</param>
public IEnumerator SendAPICall( string endpoint, string callbackObject, string callbackSuccess, string callBackError)
{
string url = baseAPIEndpoint + endpoint;
Debug.Log("Sending API Call: " + url);
// connect to the server
WWW w = new WWW( url);
// wait for the server response
yield return w;
if (w.error != null)
{
Debug.LogError("WWW result [ERROR]: " + w.error);
GameObject callback = GameObject.Find ( callbackObject);
// ok so we loaded up the json in the w.text field, send it to our callback so we can parse it into the c# object
callback.SendMessage ( callBackError, w.text, SendMessageOptions.DontRequireReceiver );
}
else
{
Debug.Log("WWW result [DONE]: " + w.text);
GameObject callback = GameObject.Find ( callbackObject);
// ok so we loaded up the json in the w.text field, send it to our callback so we can parse it into the c# object
callback.SendMessage ( callbackSuccess, w.text, SendMessageOptions.DontRequireReceiver );
}
} // end else
}// end SendAPICall
// then in our callback object, we can parse it like so:
// parse API response in our callback
public bool ParseResponse( string json)
{
int iParse;
bool bParse;
Debug.Log("Login Response result [DONE]: " + json);
var response = JSONNode.Parse(json);
// create c# data model for us to load in the response
DataModel apiResponse = new LoginResponse();
apiResponse.authenticationToken = response["authenticationToken"];
// sub c# objects as necessary
apiResponse.user = new User();
apiResponse.user.images = new List<Image>();
int.TryParse(response["user"]["imageCount"], out iParse);
apiResponse.user.imageCount = iParse;
apiResponse.user.firstname = response["firstname"];
int.TryParse(response["user"]["userId"], out iParse);
loginResponse.user.userId = iParse;
int.TryParse(response["user"]["profileId"], out iParse);
loginResponse.user.profileId = iParse;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment