How to print string from json file into TMP_Text in Unity/C#?

272 Views Asked by At

I am new in using Unity and C#. I have a code that I got from a source that reads a json file. I want the data from the json file to appear and printed on a specific textfield.

Here is my code...

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class jsonReader : MonoBehaviour
{
    public TextAsset txtjson;


    public TMP_Text desc; //TextField Object in scene

    [System.Serializable]
    public class Question
    {
        public string questiondesc;
        public string answer1, answer2, answer3, answer4;
        public int correctans;
    }

    [System.Serializable]
    public class QuestionList
    {
        public Question[] questions; 
    }

    
    public QuestionList myQuestionList = new QuestionList(); //Loads Question Array

    void Start()
    {
        myQuestionList = JsonUtility.FromJson<QuestionList>(txtjson.text);
    }
}


scene Here is a sample json...

{
    "questions": [
        {
            "questiondesc": "How tall is this... ?",
            "answer1": "1 inch",
            "answer2": "3 inches",
            "answer3": "7 inches",
            "answer4": "10 inches",
            "correctans": 1
        },

        {
            "questiondesc": "First letter of the english alphabet?",
            "answer1": "A",
            "answer2": "B",
            "answer3": "C",
            "answer4": "D",
            "correctans": 0
        }
    ]
}

For instance, I want the first question description in the json file to load in the TMP_text object.

1

There are 1 best solutions below

0
On

I'll help with few steps so you can clarify some of your problems. You have a List of question so you need to go throw them with a for loop or foreach loop then access your description text and then assign it to your text UI.

string allDescriptions = "";

foreach (var q in myQuestionList)
    {
     allDescriptions += q.questiondesc+" \n";
    }
desc.text = allDescriptions;//this will display all the question descriptions

If you want to display one specific question description make a function that take an index or an id and then like Mr. @derHugo said just call desc.text = myQuestionList.questions[someIndex].questiondesc I'll provide with an example :

public void DisplayQuestionDescription(int index)
     {
        if (string.IsNullOrEmpty(myQuestionList.questions[index].questiondesc))
         {
                        desc.text = myQuestionList.questions[index].questiondesc;
         }
         else
         {
                        desc.text = "No Description";
         }
     }

To Use this you simply call DisplayQuestionDescription(0); for example to get first question description