Unity uses the JsonFX plug-in for serialization, unityjsonfx

Source: Internet
Author: User

Unity uses the JsonFX plug-in for serialization, unityjsonfx

Sun Guangdong 2015.6.25


Unity and JSON-Quick Guide:

Compared with XML, Json is more efficient.

Introduction:

What is Json?
If you have never used it, it contains a dictionary structure. But after you serialize and deserialize some data, you will want to know how it works.


Unity does not provide a built-in solution for JSON.


Get the JsonFX of the Dark Table:

Dark Table has created a solution in Unity, JsonFx. you can get the DLL here, if you want to follow along.

Download it, drag it to the Unity project, and put it in the Plugins file.


Our Data Classes:
The readme file from the JsonFx zip file contains a list of supported data types. We will treat it as a simple base element and array-just to demonstrate the function.
I have created several classes for this example. We have a class called DataPC, which is the information we want to store for our Player Controller. The class name also mentioned is the class serialized by DataName.

I use these as data classes because their purpose is to request my JSON file, not the actual class. In other words, I may have a class that calls PC to process functions in the game, but my simple DataPC class can help to store and retrieve json-format data. This does not require any means.

The second class I created is the DataItem class, which stores the data of a specific item.

public class DataPC{    public string name;    public int maxLevel;    public string description;    public string portrait;    public DataItem[] inventory;}public class DataItem{    public string name;    public int cost;}


Here we get a little fancy: I created a DataItem array to store multiple items.


Serializing the Data:
Next, I have set up a class to process serialization and deserialization. :

using UnityEngine;using System.Collections;using JsonFx.Json;public class DataHandlerTest : MonoBehaviour {    public DataPC myPC;    void Start()    {        myPC = new DataPC();        myPC.name = "Jimbob";        myPC.maxLevel = 99;        myPC.description = "Jimbob likes beer and trucks.";        myPC.portrait = "jimbob.png";        myPC.inventory = new DataItem[2];        myPC.inventory[0] = new DataItem();        myPC.inventory[1] = new DataItem();        myPC.inventory[0].name = "Silver Bullet";        myPC.inventory[0].cost = 5;        myPC.inventory[1].name = "Shotgun";        myPC.inventory[1].cost = 200;    }    public void OnGUI()    {        if (GUILayout.Button("SERIALIZE"))        {            string myJson = JsonWriter.Serialize(myPC);            Debug.Log(myJson);        }    }}


First, we need to include the JsonFx Library: using JsonFx. Json.
Next, we create a new instance of DataPC and initialize its value. We store two Items into an array and initialize each.

In the OnGUI () method.

string myJson = JsonWriter.Serialize(myPC);Debug.Log(myJson);

What are we doing here? Serialize the class to Json and save the Json as a string. Once we have a string, we print it out to the debug log.


A small problem with this method is that it generates a JSON line without line breaks in the typographical structure. No format. This means it is a bit difficult to read when there is a large amount of data, but you can Copy this to the selected text editor, you can also use a web-based tool to do this. This sets the format to and verifies Json.

{    "name":"Jimbob",    "maxLevel":99,    "description":"Jimbob likes beer and trucks.",    "portrait":"jimbob.png",    "inventory":[       {          "name":"Silver Bullet",          "cost":5       },       {          "name":"Shotgun",          "cost":200       }    ] }

JSON De/Serialization Using Unity and JsonFx:

Purpose:
The purpose of serialized data is to allow it to be stored or shared between different systems or even applications. It creates a common data template that can be converted back and forth (serialized and deserialized) or even when the source data is not considered to be received by the system or application itself. There are various common formats (XML, CSV, binary files, or JSON in our example) that can be used to serialize data.


In our example, we want to create a class in our application; when we create its instance, it will exist in the memory until we destroy it or stop the application. Once we close the play mode in the unity Editor (or close the window generated by our build), this data will be lost. By serialization, content is transmitted to a text file in this case. Using JSON, we can store the content in the file system, not only can we edit and view changes offline reflected in our application, but when we load it again.

Download the JsonFx DLL: here


Step 1: Create a container
A container is a class used to store the data you are using in the memory. This is not the only way to do this, but because you read my wizard, My containers directly use the C # class. We have:

Sandwich. cs

using System.Collections;using System.Collections.Generic;[System.Serializable]public class Sandwich{    public string name;    public string bread;    public float price;    public List<string> ingredients = new List<string>();}


It is important to note that all fields are public! In addition, [System. Serializable] can do two things for us: it allows the fields to be serialized by JsonFx, and it also exposes these fields on the inspector panel of UNity.
Very simple, right? Okay, let's move on.


Step 2: serialize (Saving/Writing) data
Start with the code and I will explain it.
JsonTutorial. cs

using UnityEngine;using System.Collections;using System.Collections.Generic;using Pathfinding.Serialization.JsonFx;using System.IO;public class JsonTutorial : MonoBehaviour {    public string fileName;    public Sandwich sandwich;    private string PATH;    private void Start() {        PATH = Application.dataPath + "/../testData/";    }    private void OnGUI()   {        if (GUILayout.Button("SAVE")){            SerializeAndSave();        }    }    private void SerializeAndSave() {        string data = JsonWriter.Serialize(sandwich);        if(!Directory.Exists(PATH)){            Directory.CreateDirectory(PATH);        }        var streamWriter = new StreamWriter(PATH + fileName + ".txt");        streamWriter.Write(data);        streamWriter.Close();    }}


The first thing is that JsonFx dll is like this:

using Pathfinding.Serialization.JsonFx;

Of course, the specific namespace depends on the DLL. If you can find another version of dll, you will use the appropriate namespace (JsonFx. Json ).
Second, we include System. IO. This is because we will read and write files.
I will simply enter fields through Inspectors. So that you can see the output later.



There is no need to extend it, because you will notice that in the SerializeAndSave () method, we give it an automation (although you can modify the code at any time to do it ).


The following fields are defined in the container earlier.
String data = JsonWriter. Serialize (sandwich );


That line is where the sandwich object is serialized into a file. JsonFx handles heavy work for us. You can Debug. Log (data) to see how it looks, but we need to write it into a file anyway, so let's continue.


In the following lines, check whether the specified directory PATH exists and create it if it does not exist. Note that by default, Application. dataPath is the/Assets Directory of the project. I have already written it, so I just went to a directory (......), and save it to a directory of MyProject/(in this case,/Assets, basically ).


The full path used by the StreamWriter constructor, including the file name. Again, you can simply add the ". txt" extension manually, and ask the user to fill in the file name variable, but casually. You will be able to open the file in the text editor, even if you didn't give it an extension.


Test it!
Drag the JsonTutorial script as a component in any scenario and you will see a "SAVE" button (remember OnGUI ). Click the button and check your project folder. You can see the/testData path. No matter what the name is in the file set in Inspectors (in my example my_data.txt), you should see A/testData directory.

Based on my sandwich design, this file will contain the following JSON as text:

{     "name": "meatball",     "bread": "white",     "price": 5.99,     "ingredients": [        "metaballs",        "sauce",        "cheese"     ]  }


We can even exchange something a bit by providing its sandwiches instead of just a list. Let's create a simple container to store the List sandwiches (this work, because you cannot deserialize List <Sandwiches> directly.


In Sandwich. cs

[System.Serializable]public class Sandwiches{    public List<Sandwich> sandwiches = new List<Sandwich>();}


Instead, you create a new Sandwich variable that contains the List <Sandwich> in turn according to our container.

Just don't forget to change JsonWriter. Serialize (sandwich); To JsonWriter. Serialize (sandwiches); In inspector, add some sandwiches to run it and view what you get.


Step 3: Loading and Deserializing
The most difficult part is that we have everything we need, so the rest is to create a method to load data and a button to call this method.
Here is our method:
In JsonTutorial. cs

private void LoadAndDeserialize(){        var streamReader = new StreamReader(PATH + fileName + ".txt");        string data = streamReader.ReadToEnd();        streamReader.Close();        sandwiches = JsonReader.Deserialize<Sandwiches>(data);    }


It looks similar to our SerializeAndSave () method, but we read the opposite (nonsense) here ).
Opposite to StreamWriter, we are using StreamReader

In contrast to JsonWriter. Serialize, we use JsonReader. Deserialize. The syntax you will notice is a little different here, because our readers need to know what type of deserialization (in this example, Sandwiches), and you need to deserialize through it, it is a string of data we have StreamReader from back.


Step 4: test it again!

Final code
JsonTutorial. cs

using UnityEngine;using System.Collections;using System.Collections.Generic;using Pathfinding.Serialization.JsonFx;using System.IO;public class JsonTutorial : MonoBehaviour {    public string fileName;    public Sandwiches sandwiches = new Sandwiches();    //public List<Sandwich> sandwiches = new List<Sandwich>();    private string PATH;    private void Start() {        PATH = Application.dataPath + "/../testData/";    }    private void OnGUI()   {        if (GUILayout.Button("SAVE")){            SerializeAndSave();        }        if (GUILayout.Button("LOAD")){            LoadAndDeserialize();        }    }    private void SerializeAndSave() {        string data = JsonWriter.Serialize(sandwiches);        if(!Directory.Exists(PATH)){            Directory.CreateDirectory(PATH);        }        var streamWriter = new StreamWriter(PATH + fileName + ".txt");        streamWriter.Write(data);        streamWriter.Close();    }    private void LoadAndDeserialize(){        var streamReader = new StreamReader(PATH + fileName + ".txt");        string data = streamReader.ReadToEnd();        streamReader.Close();        sandwiches = JsonReader.Deserialize<Sandwiches>(data);    }}

Sandwich. cs

using System.Collections;using System.Collections.Generic;[System.Serializable]public class Sandwich{    public string name;    public string bread;     public float price;    public List<string> ingredients = new List<string>();    public Sandwich() { }}[System.Serializable]public class Sandwiches{    public List<Sandwich> sandwiches = new List<Sandwich>();}



Where to learn JsonFX: http://www.raybarrera.com/2014/05/18/json-deserialization-using-unity-and-jsonfx/
Http://www.raybarrera.com/2012/11/03/unity-and-json-quick-guide/
Https://bitbucket.org/TowerOfBricks/jsonfx-for-unity3d/overview





Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.