- Home /
How to render images from JSON in Unity?
I'm building an eCommerce app in Unity. I have built the required APIs. But I'm having some problems in rendering the JSON decoded images properly. I have tried SimpleJSON and JSONUtility, both. But still can't understand what's the issue? I think I've messed up somewhere in for-loop or JSON parsing. .
"The current problem at runtime (I want 5 unique images only)>>"
.
"This is my APIData.cs file>>"
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using UnityEngine.Networking;
using System.Collections.Generic;
using SimpleJSON;
public class APIData : MonoBehaviour
{
[Serializable]
public class Result
{
public int id;
public List<string> products;
public List<string> brands;
public List<string> advertisements;
public string name;
public bool top;
public bool featured;
public Sprite Icon;
public string image;
}
[Serializable]
public class Root
{
public int count;
public object next;
public object previous;
public List<Result> results;
}
Result[] allResults;
[SerializeField] Sprite defaultIcon;
string jsonData;
void Start()
{
Debug.Log("New Start" + allResults);
StartCoroutine(GetJsonData());
}
private IEnumerator GetJsonData()
{
string apiurl = "https://search-in-app.herokuapp.com/api/v2/products/";
UnityWebRequest request = UnityWebRequest.Get(apiurl);
request.chunkedTransfer = false;
yield return request.SendWebRequest();
//WWW www = new WWW(apiurl);
//yield return www;
if (request.result == UnityWebRequest.Result.ConnectionError)
{
Debug.Log("here"+request.error);
}
else
{
if (request.isDone)
{
JSONNode jsonNode_new = SimpleJSON.JSON.Parse(request.downloadHandler.text);
Debug.Log("JsonNode_new " + jsonNode_new["results"][3]["image"].ToString());
allResults = JsonHelper.GetArray<Result>(jsonNode_new["results"].ToString());
for (int i=0; i< allResults.Length; i++)
{
string prod_image = jsonNode_new["results"][i]["image"];
Debug.Log("After request "+allResults);
StartCoroutine(GetGamesIcones(prod_image));
}
}
}
if (string.IsNullOrEmpty(request.error))
{
// store www.text in a string type variable
jsonData = request.downloadHandler.text;
}
}
void DrawUI()
{
GameObject buttonTemplate = transform.GetChild(0).gameObject;
GameObject g;
int N = allResults.Length;
for (int i = 0; i < N; i++)
{
g = Instantiate(buttonTemplate, transform);
g.transform.GetChild(0).GetComponent<Image>().sprite = allResults[i].Icon;
}
Destroy(buttonTemplate);
}
IEnumerator GetGamesIcones(string url)
{
for (int i = 0; i < allResults.Length; i++)
{
WWW w = new WWW(url);
yield return w;
if (w.error != null)
{
//error
//show default image
allResults[i].Icon = defaultIcon;
}
else
{
if (w.isDone)
{
Texture2D tx = w.texture;
allResults[i].Icon = Sprite.Create(tx, new Rect(0f, 0f, tx.width, tx.height), Vector2.zero, 10f);
}
}
}
DrawUI();
}
}
Answer by Bunny83 · Jul 18, 2021 at 11:44 AM
But I'm having some problems in rendering the JSON decoded images properly
What exactly does "having some problems" mean exactly? Your "GetGamesIcones" method and the way you use it doesn't seem to make any sense at all. For every element in your "allResults" array you start a new coroutine. Each of those coroutines again iterates through all items again and downloads the same image n number of times and sets all the images for all elements to the same image. So if you have 10 elements you would start 10 coroutines and each will download the image 10 times. So you would download 100 images in total. This is a complete mess.
You want to download each image only once. Also depending on your backend you have to decide if you want / can download all images in parallel or not.
There are many other very dodgy things going on in your code. Your DrawUI method grabs the first child, treats it as templage and duplicates it for each element and in the end you delete that initial object. Since at the moment you call that method several times you would delete the first element several times. If you want to use a button template, create a prefab and instantiate the prefab instead. It's difficult to suggest concrete changes since the code is quite a mess and the only solution would be to completely rewrite it.
Finally your usage of SimpleJSON seems weird as well. You use it to parse all your json just to get to a certain sub node, then you let it convert it back to json just in order to parse it again with your JsonHelper class which is probably just using Unity's JsonUtility. While this usage is possible, it's quite a waste of time and resources.
So it's difficult to help you here without doing all the work for you. You certainly should look up the concept of prefabs and also think through your logic again.
I'm quite new to C# and Unity so that's why having some trouble with the syntax. Thanks for your response.
Your answer
![](https://koobas.hobune.stream/wayback/20220613040459im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
creating json for waypoints and links to them 0 Answers
Serialize a list of scriptable objects to Json 0 Answers
Looking for Code that will Read JSON files (C# code) 2 Answers