Unity uses the Jsonfx plugin for serialization

Source: Internet
Author: User

Sun Guangdong 2015.6.25


Unity and Json–quick Guide:

JSON is more efficient compared to the heavy and dense XML.

Introduction:

What is Json?
If you have never used it, the inside of it is the dictionary structure. But after you serialize and deserialize some data, you'll want to know how he works.


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


Get the Jsonfx for dark table:

Dark Table has created a solution in unity, Jsonfx. You can get the DLL in this, if you want to follow along.

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


Our Data Classes:
The Readme Readme file from the Jsonfx zip file contains a list of supported data types. We'll take it as a simple primitive and an array-just to demonstrate the functionality.
I have created a few classes for this example. We have a class called DATAPC, which is the information we want to store for our player controller. Also mentioned is the class name Dataname serialization.

I take these as data classes, because their purpose is to get my JSON file, not the actual class. In other words, I might have a class that calls a PC to handle the functionality in the game, but my simple DATAPC class can help store and retrieve JSON-formatted data. This does not need to be done by any means.

The second class I created is the DataItem class, which stores the data for 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've set up a class that handles 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 =;        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 = $;    }    public void Ongui ()    {        if (Guilayout.button ("SERIALIZE"))        {            string myjson = Jsonwriter.serialize ( MyPC);            Debug.Log (Myjson);}}}    


The first thing to note is that we need to include the Jsonfx library: using Jsonfx.json
Next, we create a new instance of the DATAPC and initialize its value. We give it two items to be stored in an array, initializing each one.

In the Ongui () method.

String Myjson = Jsonwriter.serialize (MyPC);D ebug. Log (Myjson);

What are we doing here? Serializes the class to JSON and saves the JSON as a string. Once we have the string, we print it out to debug log.


A small problem with this approach is that it generates JSON in a row, without the wrapping of the typeset structure, and so on. No formatting. This means that there is a lot of data when it is a bit difficult to read, but you can copy this to your choice of text editor, you can also use a web-based tool to do this. This sets the format to, and validates the Json.

{    "name": "Jimbob",    "Maxlevel":, "    description": "Jimbob likes beer and trucks.", "    Portrait": " Jimbob.png ",    " inventory ": [       {          " name ":" Silver Bullet ",          " cost ": 5       },       {          " name ":" Shotgun ",          " cost ": +    )}

JSON de/serialization Using Unity and Jsonfx:

Objective:
The purpose of serializing data is to enable 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) even when the source data is not considered to be received by the system or the application itself. There are various common formats that can be used (i.e., xml,csv, binary files, or in our example, JSON), serialized to data.


In our example, we are going to create a class in our application; When we create an instance of it, it will exist in memory until we destroy it or stop the application. Once we turn off play mode in the Unity Editor (or close the window in our build build), the data is lost. By serializing, in this case the content into a text file, using JSON, we can store it in the file system, not only we can edit it offline and view the changes reflected in our application 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 memory. It's not the only way to do this, but because you read my wizard, my container uses the C # class directly. 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's important to note that the fields are public. In addition, [system.serializable] can do two things for us: it allows Jsonfx to serialize the field, and it also exposes these fields on Unity's Inspector panel.
It's simple, right? Okay, let's move on.


2nd Step: Serializing (saving/writing) data
will start from the code and I'll explain.
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 to include the Jsonfx dll like this:

Using Pathfinding.Serialization.JsonFx;

Of course the specific namespace depends on the DLL, and if you can find another version of the DLL, you will pass the appropriate namespace (i.e. Jsonfx.json).
Second, we include System.IO. This is because we will read and write to the file.
I will simply fill in the fields via inspectors. So that you can see the output later.



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


The next few fields are just the ones we defined earlier in the container.
String data = Jsonwriter.serialize (sandwich);


That line, right there. Handles serializing to a file to a sandwich object. Jsonfx to handle the heavy work for us. You can Debug.Log (data) and see what it looks like, but we're going to write it to a file anyway, so let's go ahead.


The next few lines simply check if the directory where we specified the path path exists, and if it does not exist, create it. Note that by default, Application.datapath is the/assets directory for the project. I have written it down, so I just go to a directory (...) and save it to a directory I myproject/(so,/assets, basically).


The StreamWriter constructor actually takes the full path, including the file name. Again, you can simply omit to manually add the ". txt" extension and let the user fill in the filename variable, but casually. You will be able to open the file in a text editor even if you do not give it an extension.


Test it!
Just as a component in any scene, drag the jsontutorial script and you'll see a "SAVE" button (remember Ongui). Click the button and check your project folder. Can see the/testdata path, no matter what the name is in inspectors (in my example my_data.txt) set the file, you should see a/testdata directory.

Based on the sandwich I designed, the file will contain the following JSON as text:

{     "name": "Meatball",     "bread": "White",     "price": 5.99,     "ingredients": [        "Metaballs",        " Sauce ",        " cheese "     ]  }


We can even exchange things a little by providing it's sandwiches instead of just a list. Let's create a simple container to hold the list sandwiches (this works because you can't deserialize the list<sandwiches> direct request.


In Sandwich.cs

[System.serializable]public class sandwiches{public    list<sandwich> sandwiches = new List<sandwich> () ;}


Instead, you Sandwich the variable, creating a new Sandwich that in turn contains list<sandwich> according to our container.

Just don't forget to change jsonwriter.serialize (sandwich), go to jsonwriter.serialize (sandwiches), add some inspector in sandwiches, run it, and see what you get.


Step 3:loading and deserializing
To do the hardest part, we already have everything we need, so the rest is to create a method to load the data and a button to invoke the method.
Here's how we do it:
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 do it by reading the opposite (nonsense) here.
Contrary to StreamWriter, we are using StreamReader

Contrary to jsonwriter.serialize, we use the jsonreader.deserialize. You will notice that the syntax is a little different here, because our readers need to know what type to deserialize (in this case, sandwiches), and you pass it to deserialize, it is the data of the string we return from our StreamReader.


Step 4: Test it ... Once 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 NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Unity uses the Jsonfx plugin for serialization

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.