Unity的Json解析--读取Json文件

本文章由cartzhang编写,转载请注明出处。 全部权利保留。
文章连接:http://blog.csdn.net/cartzhang/article/details/50373558
做者:cartzhanghtml

Unity的Json解析<一>–读取Json文件

由于须要作一个外部文件配置,考虑了XML和Json,而5.3版本对Json作了更新,因此就尝试一下。
版本更新的Json部分介绍哦: [Unity5.3版本更新的Json部分 ]git

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

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

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

Json的在线编辑

Json parser :http://json.parser.online.fr/
Json在线编辑:http://www.kjson.com/jsoneditor/?f=1app

第二个是能够直接下载保存到本地的,此操做甚好啊!less

JsonUtility

先看看,在Unity中,咱们在其Json工具类中,可用的函数,总共就5个,好少啊!不过,simple is better.svg

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

using System;

namespace UnityEngine
{
    //
    // 摘要:
    // ///
    // Utility functions for working with JSON data.
    // ///
    public static class JsonUtility
    {
        //
        // 摘要:
        // ///
        // Create an object from its JSON representation.
        // ///
        //
        // 参数:
        // json:
        // The JSON representation of the object.
        //
        // type:
        // The type of object represented by the JSON.
        //
        // 返回结果:
        // ///
        // An instance of the object.
        // ///
        [WrapperlessIcall]
        public static object FromJson(string json, Type type);
        public static T FromJson<T>(string json);
        //
        // 摘要:
        // ///
        // Overwrite data in an object by reading from its JSON representation.
        // ///
        //
        // 参数:
        // json:
        // The JSON representation of the object.
        //
        // objectToOverwrite:
        // The object that should be overwritten.
        [WrapperlessIcall]
        public static void FromJsonOverwrite(string json, object objectToOverwrite);
        //
        // 摘要:
        // ///
        // Generate a JSON representation of the public fields of an object.
        // ///
        //
        // 参数:
        // 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.
        //
        // 返回结果:
        // ///
        // The object's data in JSON format.
        // ///
        public static string ToJson(object obj);
        //
        // 摘要:
        // ///
        // Generate a JSON representation of the public fields of an object.
        // ///
        //
        // 参数:
        // 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.
        //
        // 返回结果:
        // ///
        // The object's data in JSON format.
        // ///
        [WrapperlessIcall]
        public static string ToJson(object obj, bool prettyPrint);
    }
}

能够看到,主要就是建立对象的和变成Json格式的两个类型。函数

准备工做

咱们须要一个Json文件,这是主角啊,就是要读取其内容啊。
好了。我随便写了个,命名为Test.json放到了个人.\Assets\Resources\目录下;
Json文件内容以下:工具

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

建立对象类

首先,咱们须要建立一个对象类,用来存放从Json文本中读取的内容。
给这个类命名为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;
}

须要一个读取类

这个写了一个静态类,之后也可添加写的内容
名字为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;
    }
}

说明:代码被注释掉的部分,是从网上找的,解析Json为二进制格式,而后在反序列化为字符串,结果,多是编码格式问题,不能正确的反序列化,老是报错。
我表示无奈,只好从写实使用了StreamReader来处理。

调用

调用蛮简单的,就是在Update中,使用L键来加载Json文件。
代码以下:

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);
        }
    }


}

测试结果

在场景中,创建一个空对象,而后把ReadJson拖拽到对象上,运行,按下L键,就可使用断点查看,固然也后Log输出。

结果以下图:
Unity视图

Debug

说明

整体过程都很简单。工程就不一一上传。


如有问题,请随时联系! 很是感谢!