- Home /
Code to integrate Json database?
Hi guys
I have a Trivia Game which I made following a tutorial. In this tutorial, there is a list of 10 questions which are integrated within the main C# script. I intend to create hundreds of questions so I would like a separate database for my questions. I have transferred my questions to a Json file. The problem is that I don't know how to link my C# script to the Json file, so that questions are retrieved.
Here is the code from the tutorial:
void Start () {
for (int i = 0; i < questionNumbersChosen.Length; i++)
{
questionNumbersChosen[i] = -1;
}
questions[0] = new Question("question?", new string[] { "answer", "answer", "answer", "answer", "answer" }, 3);
chooseQuestions();
assignQuestion(questionNumbersChosen[0]);
}
I tried changing the questions bit to:
string filepath = Application.streamingAssetsPath;
DirectoryInfo dir = new DirectoryInfo(filepath);
FileInfo[] files = dir.GetFiles("*.json");
But this is not working to link my script and the database.
Any pointers would be welcome!
Thanks!
Use System.IO for File. Obtain the text from json file by using File.ReadAllText(path to json file plus name plus .json extension). Then use a json parser such as LitJson and concert the string to a JsonData object. Check the quick guide on LitJson website for a better tutorial :)
Thanks, that's really helpful. I'll give it a go! :)
Answer by savlon · Mar 06, 2016 at 08:31 PM
I will show you the method I use to obtain data from a Json file.
First you will need to download a Json parser. I personally have only used LitJson and this is what I'll show you how to use.
Drag the .dll file you downloaded into your Assets folder. It should automatically update your references, but if it doesn't then you'll need to follow the steps in the Using DLL tutorial that Unity has provided.
Next you will need to create a Json file. You can do this in any basic text editor by creating the file and saving it with the file ".json" file extension. Below I've provided you with an example.
{
"questions": [{
"question": "How much wood would a woodchuck chuck if a woodchuck could chuck wood?",
"answers": [
0,
7,
13,
27
],
"correct": 27
}, {
"question": "She sells sea shells by the sea shore, how many sea shells did she sell?",
"answers": [
1,
2.2,
27,
"Who cares!"
],
"correct": 27
}]
}
Note: Creating your own Json file with data inside of it can be confusing and you may miss minor errors, which will become a huge problem later when you try to obtain data from it. I would suggest you validate your json text every time you change something. You can validate your text here
You will need to save this json file with any name as long as the extension is .json. Make sure this file is somewhere in your Assets folder (You will need to know the path).
Now we create a simple class to load the string of the file and convert it to JsonData which is what you'll be working with.
using UnityEngine;
using System.Collections;
using System.IO;
using LitJson;
public static class JsonLoader
{
public static JsonData LoadFile (string path)
{
var fileContents = File.ReadAllText (path);
var data = JsonMapper.ToObject (fileContents);
return data;
}
}
Note: There is no error checking in the above script for simplicity sake. You should implement it to avoid Where's Wally errors.
Now we'll create a basic class to demonstrate the data we can obtain using the above code.
using UnityEngine;
using System.Collections;
using LitJson;
public class QuestionLoader
{
public QuestionLoader()
{
// Load the Json file and store its contents in a 'JsonData' variable
var data = JsonLoader.LoadFile (Application.dataPath + "/Resources/Questions.json");
// Access the "questions" array in the file and store them in a questions variable (JsonData)
var questions = data["questions"];
// Loop through all of the contents in the questions variable
for (int i = 0; i < questions.Count; i++)
{
// Obtain the current questions data
var currentQuestionData = questions[i];
// Obtain the actual question "How much wood would..."
var question = currentQuestionData["question"];
// Obtain the answers "0, 7, 13..."
var answers = currentQuestionData["answers"];
// Obtain the correct answer "27"
var correct = currentQuestionData["correct"];
// Print the contents to the Debug Console
Debug.Log (string.Format ("Question: {0}\nAnswers: {1}, {2}, {3}, {4}\nCorrect: {5}",
question, answers[0], answers[1], answers[2], answers[3], correct));
}
}
}
Once again, I have not added any error checking as it may be a little overwhelming as it is. I have commented the code for you so you may need to study the json file and the code to figure out what is happening.
From here you're on your own. I suggest you check out LitJson's Quickstart Guide for more information on loading and saving data.
Goodluck!
Edit: Here are the results of the above code
Question: How much wood would a woodchuck chuck if a woodchuck could chuck wood?
Answers: 0, 7, 13, 27
Correct: 27
Question: She sells sea shells by the sea shore, how many sea shells did she sell?
Answers: 1, 2.2, 27, Who cares!
Correct: 27
Wow, thank you so much, that is very generous of you! I did spend most of the day trying to work this out. I managed the questions part but not the answers. So this is going to be great! :)
You're welcome. If your database of questions is going to be rather large, I would consider using naphier's method using Sql. As he states, you won't need to load the entire database into memory prior to viewing some of its contents. At the end of the day there are still uses for loading and saving to json file. :)
Answer by Naphier · Mar 06, 2016 at 09:28 PM
http://docs.unity3d.com/Manual/JSONSerialization.html
Unity now has a built-in json serializer. It does not do dictionaries so you will need to implement your own ISerializationCallbackReceiver interface implementation in your json object class. For a dictionary, this amounts to two Lists per dictionary (one for the dictionary's keys and another for its values). There are examples of this for ScriptableObject serialization if you need it.
That said:
Editing json can be a pain. If you're transferring data to a server definitely use it, but if this is a local static database consider an easier format for a database. SQLite4Unity is nice. It also gives you the power of SQLite queries instead of having to load the entire database into classes/objects.
Brilliant, I'll look into this too! What would be the advantage of having my database on a server? And thanks for the reply! :)
Your answer
Follow this Question
Related Questions
How to add images to answers within a quiz game? 0 Answers
How to make Match 3 versus game AI C#? 0 Answers
Randomizing numbers on a list. 4 Answers
How to check the result after playing in quiz game?[Solve] -1 Answers