Updated February 21, 2023
Introduction to Unity JSON
Unity JSON can be understood as converting data into coded language in a human-readable format. In unity, one can find class JsonUtility and static methods that can work with JSON. We can serialize and deserialize with it into JSON or JSON based on a simple data structure in C#. JsonUtility works the same as Binary Formatter, as it combines with other classes such as write files and files to read. You may face the same warning such as ‘Files on a User’s system.’ This error state that the file is from a user or system and can be edited by any process, so it is not secure.
What is JSON?
JSON stands for JavaScript Object Notation and can be understood as standard open file format and data interchange format. It is used to create human-readable text that stores and transmits data of objects associated with pairs of attribute values and arrays.
How to Use Parse Unity JSON?
By using Json.Net Newtonsoft in Unity, you can quickly parse JSON. You can go with the following steps if you want to go without using a third party plugin.
Step 1: First, prepare your JSON sample, which means host or locally store it. Here is the sample.json file, which we will use for parsing purposes.
Code:
{"Values":[{
"Text":"aii"
},
{
"Text":"bii"
},
{
"Text":"cii"
},
{
"Text":"dii"
},
{
"Text":"eii"
}]
}
Step 2: The next step is to create data model classes that depend on your JSON and the serialization of those classes.
Following will be classes for the above-mentioned JSON.
Code:
[Serializable]
public class ListItem {
public Values[] Values;
}[Serializable]
public class Values
{
public string Text;
}
Here, the variable’s names should be the same as we use in JSON. For example, “Values” is the key in JSON, so the variable’s name should also be the same as we use in the “ListItem” class. If you do not keep this rule in your mind, you won’t be able to parse the JSON.
Step 3: Now, let us see the next step. Use route class to start parsing JSON. Here in this example List item is our root class, and we use it to parse is JSONUtility. Once you have your JSON in the string variable, start parsing JSONUtility. You can put this string variable by downloading JSON.
Below is the required syntax:
Syntax:
"JsonUtility.FromJson<RootClass>(smapleJSONstringVariable)"
ListItem items = JsonUtility.FromJson<ListItem>(json);
Debug.Log(items.Values,Length);
For(int I = 0;i<items.Values.Length;i++)
{
Debug.Log(items.Values.Lenght;i++)
}
Unity JSON Export
For exporting scene to JSON file format we use UnityToJSON exporter. Currently, it exports the following JSON file which can easily process:
- Nodes
- Lights
- Meshes
- Shaders
- Textures
- Light Maps
- Components
- Skeletal Meshes
- Materials
- Animation Clips
- Physics
- Cameras
- Terrain
Example:
Code:
"name": "EmptyScene",
"resources": {
"textures": [],
"lightmaps": [],
"shaders": [],
"materials": [],
"meshes": []
},
"hierarchy": [
{
"name": "Main Camera",
"components": [
{
"localPosition": [
0.0,
1.0,
-10.0
],
"localRotation": [
0.0,
0.0,
0.0,
1.0
],
"localScale": [
1.0,
1.0,
1.0
],
"name": null,
"parentName": null,
"type": "Transform"
},
{
"type": "Camera"
}
],
"children": []
},
{
"name": "Directional Light",
"components": [
{
"localPosition": [
0.0,
3.0,
0.0
],
"localRotation": [
0.408217937,
-0.234569728,
0.109381676,
0.875426054
],
"localScale": [
1.0,
1.0,
1.0
],
"name": null,
"parentName": null,
"type": "Transform"
},
{
"color": [
1.0,
0.956862748,
0.8392157,
1.0
],
"range": 10.0,
"lightType": "Point",
"castsShadows": true,
"realtime": false,
"type": "Light"
}
],
"children": []
}
]
}
Unity JSON Text Files
Now let’s see about text files of json. The C# class files help you to access files without any concern about is it locally or remotely. The C# offers us two methods to work with them which will be part of the File class: ReadAllText() and WriteAllText(). One should note that System.IO is namespace and our File is part of this. It is a collection of classes and is a method that connects with input (“I”) and output (“O”). We need namespace when we create any new component of the script in unity.
1. JSON File location in Unity
When we start running the unity project, You will find a field called ApplicationBe.persistentataPath that can be set with the currently present “persistent” directory. You can understand this set as a part we use only for initializing the system within Unity. This will show a message such as the methods Awake() or Star(), and it will be in the script component.
2. Text Files (Reading and Writing)
When we start working with the file, the first step is to open the related file and then work on it. Once you have done it, close it for further process. So for it we use methods ReadAllText() and then WriteAllText(). So the file can be read or written and handled for the purpose of opening or closing on an internal basis.
Code:
// Add System.IO to work with files!
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameDataManager : MonoBehaviour
{
// Create a field for the save file.
string saveFile;
void Awake()
{
// Update the path once the persistent path exists.
saveFile = Application.persistentDataPath + "https://cdn.educba.com/gamedata.json";
}
public void readFile()
{
// Does the file exist?
if (File.Exists(saveFile))
{
// Read the entire file and save its contents.
string fileContents = File.ReadAllText(saveFile);
// Work with JSON
}
}
public void writeFile()
{
// Work with JSON
// Write JSON to file.
File.WriteAllText(saveFile, jsonString);
}
Unity JSON Data Serialization
JSON Serialization is used for the JsonUtility class that helps convert unity objects to JSON, and JSON such as JSON Serialization can use to interact with web services. Not only this, but you can also pack and unpack text-based data. JSON Serialization uses Notion of “structured” JSON. Here a class or structure can be created according to what variables are stored in your JSON data.
Example:
Code:
[Serializable]
public class MyClass
{
public int level;
public float timeElapsed;
public string playerName;
}
Here you can understand plain C# class contains three variables such as level, timeElasped, and playerName and it is marked with a serializable attribute so that it can work with the JSON serializer.
Example:
Code:
MyClass myObject = new MyClass();
myObject.level = 1;
myObject.timeElapsed = 47.5f;
myObject.playerName = "Dr Charles Francis";
Then go with JsonUtility.ToJson method to serialize it to the JSON format:
string json = JsonUtility.ToJson(myObject);
// json now contains: '{"level":1,"timeElapsed":47.5,"playerName":"Dr Charles Francis"}'
You can also convert the JSON back into object by using JsonUtility.FromJson:
myObject = JsonUtility.FromJson<MyClass>(json);
Conclusion
We saw all possible aspects of unity JSON and how it works in concern of it. Here you just have to understand the terms of JSON and then can easily start working with it by using codes of it one by one. So try it with the script of your developed game of unity.
Recommended Articles
This is a guide to Unity JSON. Here we discuss the introduction, and how to use parse unity JSON? export, text files, and data serialization. You may also have a look at the following articles to learn more –