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 *= -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!

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][1] 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][2] 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][3]

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*;*

// 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}
Answers: {1}, {2}, {3}, {4}
Correct: {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][4] 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
[1]: https://lbv.github.io/litjson/
[2]: Unity - Manual: Managed plug-ins
[3]: http://jsonlint.com/
[4]: https://lbv.github.io/litjson/docs/quickstart.html

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.