@Henry-Smith said in Recommended way to read Entity data? (Unity, C#):
Sorry to bring back an old thread, but I'm just learning the platform and I thought I'd share my solution to this.
First, define a generic class to handle the raw json response data:
eg. my Tut1_AddTwoNumbers api returns:
{"data":{"response":{"answer":24},"success":true},"status":200}
public class Response<T>
{
public ResponseData<T> data;
public int status;
}
public class ResponseData<T>
{
public T response;
public bool success;
}
Then for each api call that you have, define a class that contains the fields that are custom to that response.
public class Tut1_AddTwoNumbersResponse
{
public int answer;
}
Now, you call your function and handle the response like this:
public void Tut1_AddTwoNumbers()
{
string scriptName = "Tut1_AddTwoNumbers";
// Anonymous object to supply the params.
var data = new
{
num1 = 16,
num2 = 8
};
var jsonScriptData = JsonWriter.Serialize(data);
SuccessCallback successCallback = (response, userdata) =>
{
var responseObject = JsonReader.Deserialize<Response<Tut1_AddTwoNumbersResponse>>(response);
//var responseObject = JObject.Parse(response);
Debug.Log($"Success The answer is '{responseObject.data.response.answer}' | raw_json={response}");
};
FailureCallback failureCallback = (status, code, error, userdata) =>
{
Debug.Log(string.Format("Failed | {0} {1} {2}", status, code, error));
};
// Call the script
_bc.ScriptService.RunScript(scriptName, jsonScriptData, successCallback, failureCallback);
}
this line is the important part:
JsonReader.Deserialize<Response<Tut1_AddTwoNumbersResponse>>(response);
Hope that helps someone!