This is the fourth day of my participation in the August More text Challenge. For details, see:August is more challenging

An overview of the

Json is a lightweight text data format that is widely used in projects. In Unity development process is usually used for communication data interaction, as well as configuration file read and write operations. This article focuses on what Json is and how it can be easily used in Unity.

Json is introduced

JSON is short for JavaScript Object Notation, a text format for data exchange. It is based on a subset of ECMAScript, the JS specification developed by the W3C, and uses a text format that is completely independent of the programming language to store and represent data. The simplicity and clarity of the hierarchy make JSON an ideal data exchange language. Easy to read and write, but also easy to machine parsing and generation, and effectively improve the network transmission efficiency.

The characteristics of the Json

Json has the following features that make it an ideal data exchange language:

  • Json is a lightweight text data exchange format
  • Json is self-descriptive and easier to understand
  • Json takes a completely language-independent text format: Json uses JavaScript syntax to describe data objects, but Json is still language – and platform-independent. Json parsers and Json libraries support many different programming languages. The current common dynamic programming languages (PHP, JSP,.NET) all support Json.

Json is a syntax for storing and exchanging textual information. It has the same characteristics as XML, is a data storage format, but is smaller, faster, easier for humans to write and read, and easier to generate and parse than XML.

Using JSON in Unity

In Unity, Json is one of the most commonly used file formats, but the Unity engine and C# language itself does not provide a convenient interface for the use of Json, often known as LitJson is a popular Unity plug-in, can be convenient, fast conversion between Json and objects.

The LitJson plug-in is a Dll file. Create a new Plugins directory under project Assets, import litjson.dll into it, and then introduce its namespace into the calling code

using LitJson;;

Convert a Json string of type string to Json data and parse it

In the development process, we often send data in Json strings. When the data is sent, it may become a string. In this case, we need to convert it into Json data and parse it. So let’s say I have this string of data

String data = “{\” name \ “: \” zhang SAN \ “, \ “student id \” : \ “20210101 \”, \ \ “class” : \ “three years one \”, \ \ “age” : \ “22 \”} “;” \” is an escape character

Now it’s time to convert it into Json data and parse it in Unity. Start by defining a class to store the information

public class StudentInfo { public string Name { get; set; Public string Number {get; set; } public string Class {get; set; } public int Age {get; set; Public void Info(string name, string number, string _class, string age) {this. name = name; this.Number = number; this.Class = _class; this.Age = int.Parse(age); }}Copy the code

Next we need to parse the data with a reference to LitJson

JsonData jsonData = JsonMapper.ToObject(data); StudentInfo StudentInfo = new StudentInfo(); Studentinfo.info (jsonData[" name "].toString (), jsonData[" student number "].toString (), jsonData[" class "].toString (), jsonData[" class "].toString (), JsonData [r]. "age" ToString ()); // Pass in the debug.log (studentinfo.name + "," + studentinfo.number + "," + studentinfo.class + "," + studentinfo.age);Copy the code

So you can parse the data out and run it in Unity and the result is

Reading a JSON file

This is not much different from the previous method, except that it reads json data, converts it to a data stream, converts it to JSON data, and then parses it. The first choice is to determine whether the file exists, and then to read

string path = Application.streamingAssetsPath +"/Config/JsonModel.json"; if(! File.Exists(path)) { return; } StreamReader streamreader =new StreamReader(Application.streamingAssetsPath +"/Config/JsonModel.json"); // Read the data and convert it into a data streamCopy the code

The data is then transformed and parsed as described above

JsonReader js =new JsonReader(streamreader); StudentInfo = jsonMapper. ToObject< studentInfo >(js); Streamreader.close (); streamReader.close (); streamreader.Dispose();Copy the code

Writing to Json (new or Update)

First read the local file to see if it exists, and then define a class before proceeding

public class StudentList
{ 
    public Dictionary<string, string> dictionary = new Dictionary<string, string>(); 
}
Copy the code

And then get the path

string path = Application.streamingAssetsPath +"/Config/JsonModel.json";
Copy the code

Check whether the File Exists by using file.exists (filePath). If update key pairs exist, create them if they do not exist

public StudentList studentList = new StudentList();
Copy the code
if (! File. The Exists (filePath)) / / there is no create keys for {studentList. Dictionary. The Add (" Name ", studentInfo. Name); studentList.dictionary.Add("Number", studentInfo.Number); studentList.dictionary.Add("Class", studentInfo.Class); studentList.dictionary.Add("Age", studentInfo.Age.ToString()); } else {studentList. Dictionary ["Name"] = studentinfo.name; studentList.dictionary["Number"] = studentInfo.Number; studentList.dictionary["Class"] = studentInfo.Class; studentList.dictionary["Age"] = studentInfo.Age.ToString(); }Copy the code

Then the data is saved

FileInfo file = new FileInfo(filePath); StreamWriter sw = file.createText (); StreamWriter sw = file.createText (); String JSON = jsonMapper.tojson (studentList.dictionary); // Save the converted string to a file sw.writeline (json); Sw.close (); sw.Dispose(); // Refresh the resource assetDatabase.refresh ();Copy the code

At this point, the Json file is written.

Write in the last

All the shared content are the author in the daily development process used a variety of small function points, share out also in a disguised review, if there is a bad place to write also please give advice. The source code of the Demo will be sorted out and shared later.