Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by raguelmoon · Oct 19, 2016 at 01:34 PM · c#jsonlist of lists

error in c# for creating list of quiz data

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

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by InfiniBuzz · Oct 19, 2016 at 02:11 PM

You need to instantiate the quiz.Ans List just as you do it with the quizList. That means you need to quiz.Ans = new List<string>(); somwhere, otherwise it is never being instantiated and therefore is null. EDIT: I would recommend you to do this in the QuizData class constructor:

 public class QuizData
  {
      public string id { get; set;}
      public string Q { get; set;}
      public List<string> Ans { get; set;}
      public QuizData()
      {
           Ans = new List<string>();
      }
 
  }



EDIT: as of your 2nd question I'm not sure if I understand you correctly.

But what you probably want is a list of all QuizData objects. Did you try the following:

 public void JData () {
          string filePath = System.IO.Path.Combine (Application.streamingAssetsPath, "Test 1.json");
          jsonString = System.IO.File.ReadAllText (filePath);
          quizList = JsonMapper.ToObject<QuizDataRoot>(jsonString);
 
 }

Where QuizDataRoot is:

 public class QuizDataRoot {
     public List<QuizData> data { get; set; }
 }

And then for debugging:

 void Start() {
          JData ();
          Debug.Log (quizList [2].Q); //print question number 3
          foreach(QuizData quizData in quizList) {
                Debug.Log(quizData.id+", "+quizData.Q);
                foreach(string a in quizData.Ans) {
                     Debug.Log(a);
                }
          }
 }

Hope this helps

Comment
Add comment · Show 6 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image raguelmoon · Oct 19, 2016 at 04:29 PM 0
Share

Thank you very much infiniBuzz! It solved my problem. But now I have another issue. When I print out the question with 4 options on screen then it prints same four option for all questions:

 void Start() {
         JData ();
         Debug.Log (quizList [2].Q); //print question number 3
         for (int i = 0; i < 4; i++) {            
             Debug.Log (quizList [2].Ans [i]); //it prints only first four options for all questions.
         }
     }


Is there any other way to handle the data so that I can randomize the question in list and also can shuffle the options? Thank you very much! Ram

avatar image InfiniBuzz raguelmoon · Oct 19, 2016 at 05:35 PM 0
Share

See my updated answer. Is that what you try?

avatar image raguelmoon · Oct 19, 2016 at 05:49 PM 0
Share

Dear infiniBuzz! When I modify code as you suggested then I get error:

ArgumentOutOfRangeException: Argument is out of range. Parameter name: index

When when I remove the line

Debug.Log (quizList [2].Q); //print question number 3

in void start(), and then run the program, it shows nothing without errors. it looks that list is empty. Please help me, thank you, Ram

avatar image InfiniBuzz raguelmoon · Oct 19, 2016 at 06:24 PM 0
Share

I edited my answer again.

avatar image raguelmoon InfiniBuzz · Oct 19, 2016 at 06:48 PM 0
Share

Dear InfiniBuzz! Thank you for help, but at this this I get this error:

error CS0029: Cannot implicitly convert type QuizBank.QuizDataRoot' to System.Collections.Generic.List'

Thank you, Ram

Show more comments
avatar image
0

Answer by raguelmoon · Oct 19, 2016 at 07:04 PM

Dear InfiniBuzz!!

Thank you very much, a lot of thanks...

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image InfiniBuzz · Oct 19, 2016 at 07:11 PM 0
Share

So, I assume it worked :) You're welcome. You can mark the answer as accepted so it does not show up as unanswered.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Get Yelp API via Oauth in Unity- signature help needed 2 Answers

Loading JSON as a Text Asset using Resources.Load 1 Answer

Pass values as bool or number type using SimpleJSON 0 Answers

How do you sort a list of JSONNodes by key value? 1 Answer

Application.persistentDataPath 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges