How to read a list

How do I read a JSON list?

string s = www.downloadHandler.text;
            Questions data = JsonUtility.FromJson<Questions>(s);
            // read the "data.questions" list and do what you've done with your old list.
    IEnumerator getData()
    {
        UnityWebRequest www = UnityWebRequest.Get("http://localhost/camelrace/GetQuestions.php");
        yield return www.SendWebRequest();
        if (www.isHttpError || www.isNetworkError)
        {
            Debug.Log("Connection Error");
        }
        else
        {
            string s = www.downloadHandler.text;
            Questions data = JsonUtility.FromJson<Questions>(s);
            // read the "data.questions" list and do what you've done with your old list.
        
        
            // You probably want to copy "data.questions" into your "QnA" list.
        }
    }
    [System.Serializable]
    public class Questions
    {
        public List<QuestionAndAnswers> questions;
    }
[System.Serializable]
public class QuestionAndAnswers
{



}
//Convert object / array into JSON
$qList = array();
while($row = $result->fetch_assoc()) {
    $item = array(
        'Question'=>$row["question"],
        'Answers'=>array($row["answer_one"], $row["answer_two"], $row["answer_three"]),
        'CorrectAnswer;' => $row["correct_answer"]
    );
    $qList[] = $item;
}
echo json_encode(array('questions' => $qList));

bump

To read from Json you need to declare a plane .cs class which matches the Json, that way you can cast the result to the class and read from it :slight_smile:

Problems with Unity “tiny lite” built-in JSON:

In general I highly suggest staying away from Unity’s JSON “tiny lite” package. It’s really not very capable at all and will silently fail on very common data structures, such as Dictionaries and Hashes and ALL properties.

Instead grab Newtonsoft JSON .NET off the asset store for free, or else install it from the Unity Package Manager (Window → Package Manager).

Also, always be sure to leverage sites like:

https://csharp2json.io

1 Like