Dear all,
I am storing json quiz data into list using C# but I get error. Here is json file and two c# scripts:
Json file:
{
"data":[
{
"id":"1",
"Q":"Mechanics deals with the study of",
"Ans":[
"motion of bodies",
"origin of universe",
"machines",
"heat energy"
]
},
{
"id":"2",
"Q":"Electrons were discovered by",
"Ans":[
"JJ Thomson",
"Rutherford",
"Max Plank",
"Einstein"
]
},
{
"id":"3",
"Q":"The SI unit of electric current is",
"Ans":[
"Ampere",
"Volt",
"Watt",
"KWH"
]
},
{
"id":"4",
"Q":"which one is not base quantity?",
"Ans":[
"force",
"mass",
"time",
"distance"
]
},
{
"id":"5",
"Q":"which of the following is not a unit of time?",
"Ans":[
"Light Year",
"Year",
"Second",
"microsecond"
]
},
{
"id":"6",
"Q":"Newton-sec is unit of",
"Ans":[
"linear momentum",
"force",
"work",
"power"
]
},
{
"id":"7",
"Q":"Era of modern physics begins from:",
"Ans":[
"1900",
"1800",
"1924",
"1979"
]
},
{
"id":"8",
"Q":"Special Theory of relativity was given out by Einstein in",
"Ans":[
"1905",
"1916",
"1901",
"1924"
]
},
{
"id":"9",
"Q":"Einstein received Noble Prize on his work on:",
"Ans":[
"Photoelectric effetc",
"Special Theory of Relativity",
"General Theory of Relativity",
"E=mc²"
]
}
]
}
c# class :
using System.Collections.Generic;
public class QuizData
{
public string id { get; set;}
public string Q { get; set;}
public List<string> Ans { get; set;}
}
//C# file which handles data:
using UnityEngine;
using System.Collections;
using System.IO;
using LitJson;
using UnityEngine.UI;
using System.Collections.Generic;
public class QuizBank : MonoBehaviour {
public string jsonString;
public JsonData qData;
public int q_counter=1;
public int quizTotal;
public QuizData quiz = new QuizData();
public List<QuizData> quizList = new List<QuizData> ();
public void JData () {
string filePath = System.IO.Path.Combine (Application.streamingAssetsPath, "Test 1.json");
jsonString = System.IO.File.ReadAllText (filePath);
qData = JsonMapper.ToObject (jsonString);
for (int i = 0; i < 5; i++) {
quiz.Q= qData ["data"] [q_counter] ["Q"].ToString ();
for (int j = 0; j < 4; j++) {
quiz.Ans.add((qData ["data"] [q_counter] ["Ans"] [j].ToString ()));
}
quizList.Add(quiz);
q_counter++;
}
}
}
But I get error “Object reference not set to an instance of an object” at the line where i add “quiz.Ans.add”.
Any help would be appreciated.
Thank you,
Ram