Unity's Json parsing < 1 > -- Read Json files

Keywords: JSON Unity Attribute github

This article was written by cartzhang. Please indicate the source for reprinting. All rights reserved. -
Links to articles: http://blog.csdn.net/cartzhang/article/details/50373558 
Author: cartzhang

Unity's Json parsing < 1> - Read Json files

Because you need to make an external file configuration, considering XML and Json, and version 5.3 updates Json, so try it. -
The Json section of the version update introduces: [Json section of Unity 5.3 update]

https://github.com/cartzhang/UnityJsonTest/blob/master/Assets/JSONSerialization.html

https://unity3d.com/cn/unity/whats-new/unity-5.3

https://blogs.unity3d.com/cn/2015/12/08/unity-5-3-all-new-features-and-more-platforms/

Json's online editing

Json parser :http://json.parser.online.fr/ 
Json Online Editor: http://www.kjson.com/jsoneditor/?f=1

The second is that it can be downloaded and saved locally. This operation is very good.

JsonUtility

First, in Unity, we have five functions available in its Json tool class. How many! However, simple is better.

#region Assembly UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// H:\Unity\Project\JsonReadTest\Library\UnityAssemblies\UnityEngine.dll
#endregion

using System;

namespace UnityEngine
{
    //
    // Summary:
    //     ///
    //     Utility functions for working with JSON data.
    //     ///
    public static class JsonUtility
    {
        //
        // Summary:
        //     ///
        //     Create an object from its JSON representation.
        //     ///
        //
        // Parameters:
        //   json:
        //     The JSON representation of the object.
        //
        //   type:
        //     The type of object represented by the JSON.
        //
        // Returns the result:
        //     ///
        //     An instance of the object.
        //     ///
        [WrapperlessIcall]
        public static object FromJson(string json, Type type);
        public static T FromJson<T>(string json);
        //
        // Summary:
        //     ///
        //     Overwrite data in an object by reading from its JSON representation.
        //     ///
        //
        // Parameters:
        //   json:
        //     The JSON representation of the object.
        //
        //   objectToOverwrite:
        //     The object that should be overwritten.
        [WrapperlessIcall]
        public static void FromJsonOverwrite(string json, object objectToOverwrite);
        //
        // Summary:
        //     ///
        //     Generate a JSON representation of the public fields of an object.
        //     ///
        //
        // Parameters:
        //   obj:
        //     The object to convert to JSON form.
        //
        //   prettyPrint:
        //     If true, format the output for readability. If false, format the output for minimum
        //     size. Default is false.
        //
        // Returns the result:
        //     ///
        //     The object's data in JSON format.
        //     ///
        public static string ToJson(object obj);
        //
        // Summary:
        //     ///
        //     Generate a JSON representation of the public fields of an object.
        //     ///
        //
        // Parameters:
        //   obj:
        //     The object to convert to JSON form.
        //
        //   prettyPrint:
        //     If true, format the output for readability. If false, format the output for minimum
        //     size. Default is false.
        //
        // Returns the result:
        //     ///
        //     The object's data in JSON format.
        //     ///
        [WrapperlessIcall]
        public static string ToJson(object obj, bool prettyPrint);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90

As you can see, the main two types are creating objects and changing to Json format.

Dead work

We need a Json file, which is the protagonist, just to read its content. -
Okay. I randomly wrote one, named Test.json, and put it in my. Assets Resources directory.
The Json file reads as follows:

{"gameName":"JSON Serializer Test","version":"1.0","isStereo":"false","isUseHardWare":"true","statusList":[{"name":"test","id":"1u702"}]}
  • 1

Create object classes

First, we need to create an object class to store what we read from Json text. -
Name this class GameStatus.cs

using UnityEngine;
using System;
using System.Collections;

[Serializable]
public class GameStatus
{
    public string gameName;
    public string version;
    public bool isStereo;
    public bool isUseHardWare;
    public refencenes[] statusList;
}

[Serializable]
public class refencenes
{
    public string name;
    public int id;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

Need a read class

This has written a static class, which can be added later.
The name is LoadJson.cs

using UnityEngine;
using System.Collections;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public class LoadJson : MonoBehaviour
{
    public static GameStatus LoadJsonFromFile()
    {
        BinaryFormatter bf = new BinaryFormatter();

        if (!File.Exists(Application.dataPath + "/Resources/Test.json"))
        {
            return null;
        }

        StreamReader sr = new StreamReader(Application.dataPath + "/Resources/Test.json");

        //FileStream file = File.Open(Application.dataPath + "/Test.json", FileMode.Open, FileAccess.ReadWrite);
        //if (file.Length == 0)
        //{
        //    return null;
        //}

        //string json = (string)bf.Deserialize(file);
        //file.Close();

        if (sr == null)
        {
            return null;
        }
        string json = sr.ReadToEnd();

        if (json.Length > 0)
        {
            return JsonUtility.FromJson<GameStatus>(json);
        }

        return null;
    }
}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

Explanation: The part of the code that has been commented out is found on the internet. It parses Json into binary format and then deserializes it into a string. The result may be the coding format problem. It can't be deserialized correctly and always reports errors. -
I expressed frustration and had to use StreamReader to deal with it realistically.

call

The call is quite simple, that is, in Update, use the L key to load the Json file. -
The code is as follows:

using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class ReadJson : MonoBehaviour
{

    void  Update()
    {
        if(Input.GetKeyDown(KeyCode.S))
        {
            //Save();
        }

        if (Input.GetKeyDown(KeyCode.L))
        {
            GameStatus status = LoadJson.LoadJsonFromFile();
            Debug.Log(status);
        }
    }


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

test result

In the scenario, create an empty object, drag ReadJson onto the object, run, press the L key, you can use breakpoints to view, of course, after Log output.

The results are as follows:

Explain

The overall process is simple. The project will not be uploaded one by one.

If you have any questions, please feel free to contact us. -
Thank you very much.

Posted by AncientSage on Wed, 02 Jan 2019 14:09:09 -0800