- Home /
Use the data received from WWW in UI
I have an API and whenever I hit it I get the following response :
{ "current_points": 2300, "tasks": [ { "title": "Fire a player", "points": 200, "completed": true }, { "title": "Buy a player", "points": 200, "completed": true }, { "title": "Press conference", "points": 1000, "completed": false }, { "title": "Set lineup", "points": 500, "completed": false }, { "title": "Win a match", "points": 200, "completed": false } ] }
Now I want to break up this data and use it to update my UI in my gameover screen. I know I have to use JSON to break this up but the problem is I don't know how to break this up so that I can get all the tasks separately. This is my first time working with API so any help will be appreciated.
Answer by Casiell · Nov 07, 2018 at 01:31 PM
What I always do is create a class(es) that match the response I would get from API. In your case it would look like this:
public class Task
{
public string title { get; set; }
public int points { get; set; }
public bool completed { get; set; }
}
public class RootObject
{
public int current_points { get; set; }
public List<Task> tasks { get; set; }
}
Now just use a JSON library (I believe there is something built in Unity) to convert your JSON string to an instance of this class. When you have an instance you can just assign whatever property to any UI field you want.
For example if you want to assign total points to a text field, you would do:
RootObject myJsonObject;
//convert JSON to object here
MyTextField.text = myJsonObject.current_points.ToString();
This is absolutely correct, although I would recommend to NOT use Unity's built-in solution, JsonUtility.
Ins$$anonymous$$d, use something like SimpleJSON. It's free, and it's way better.
Hope that helps!
Cheers,
~LegendBacon
I am having some problems with the syntax of simpleJSON, it will be helpful if you can guide me to a tutorial of that.
I am also trying to search for a method where I can just use the nested JSON values and assign them to strings using loops without using any classes. I have seen someone do it 2-3 years back but I can't seem to recall how. If you can help me with an example of that it would be great too.
Your answer
Follow this Question
Related Questions
API with Key Headers required 0 Answers
How to use POST service using www class? 0 Answers
Unable to call external API (IBM Watson) via HTTP request? 1 Answer
Coroutine for WWW call not resuming 0 Answers
Calling API via proxy 0 Answers