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

12 篇文章 1 订阅
10 篇文章 0 订阅

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

因为需要做一个外部文件配置,考虑了XML和Json,而5.3版本对Json做了更新,所以就尝试一下。 
版本更新的Json部分介绍哦: [Unity5.3版本更新的Json部分 ]

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的在线编辑

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

第二个是可以直接下载保存到本地的,此操作甚好啊!


JsonUtility

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

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

可以看到,主要就是创建对象的和变成Json格式的两个类型。

准备工作

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

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

创建对象类

首先,我们需要创建一个对象类,用来存放从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;
}


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

需要一个读取类

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

说明:代码被注释掉的部分,是从网上找的,解析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);
        }
    }


}
 
 
  • 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
  • 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

测试结果

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

结果如下图: 
Unity视图

Debug

Unity的Json解析<二>–写Json文件

上篇做了对Json格式文件读操作, 
链接地址:http://blog.csdn.net/cartzhang/article/details/50373558

本章对Json的写文件,做个处理. 
写文件也非常简单,把大象装冰箱一样,分三步, 
创建文件, 
把内容写入文件, 
然后关闭文件.

内容

我们要处理的是所写的内容,我们打算写什么都Json文件中呢? 
我们打算把昨天的格式继续利用,还记得GameStatus ,这个是我修改的.不过,还算好用啊. 
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 refencenes()
    {
        name = "";
        id = -1;
    }

    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
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 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

写Json格式

写JSon格式呢,我看网上都用的BinaryFormatter来处理,但是我发现这个跟昨天的问题类型,要是用BinaryFormatter的话,等保存好的Json文本打开后,各种空格,NULL和乱码.这个主要是编码格式的问题. 
所以,我拒绝使用它了.

我使用File,直接WriteALLText来处理.

代码如下:

    public void SaveJson()
    {
        string json = JsonUtility.ToJson(gameStatus);
        string savePath = Application.dataPath + "/Resources/Test01.json";
        File.WriteAllText(savePath, json, Encoding.UTF8);        

        Debug.Log("save:::" + savePath);
    }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

这样就完成了写文件是否很简便呢??!!!

写Json的完整代码

完整代码如下:

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

public class WriteJson : MonoBehaviour
{
    public GameStatus gameStatus;
    public GameObject[] objects;
    void Start()
    {
        gameStatus = new GameStatus();
        gameStatus.statusList = new refencenes[objects.Length];
        gameStatus.gameName = "JSON Write Test";

        for (int i = 0; i < objects.Length; i++)
        {
            gameStatus.statusList[i] = new refencenes(); 
            gameStatus.statusList[i].id = i;
            gameStatus.statusList[i].name = objects[i].name;
        }
    }

    public void SaveJson()
    {
        string json = JsonUtility.ToJson(gameStatus);
        string savePath = Application.dataPath + "/Resources/Test01.json";
        File.WriteAllText(savePath, json, Encoding.UTF8);        

        Debug.Log("save:::" + savePath);
    }
}

 
 
  • 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
  • 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

怎么使用?

我建立了一个测试工程. 
只能如图了: 
Json读

你依然可以看到昨天写文件的痕迹.

当然我们只关注写Json了.

在writeJson的属性面板上,可看到,给它的Objects拖拽了一个cube,一个Capsule,作为保存到JSon文件中的内容的一部分.

然后在运行Unity 编辑器时,按下”S”,保存键,就会在当前工程下的\Assets\Resources\中,产生了一个Test01.json的文件,这个代码中可以看到的,你可随意修改.

结果

让我们来看看我们都保持都Json文件中了什么东西.

{"gameName":"JSON Write Test","version":"","isStereo":true,"isUseHardWare":false,"statusList":[{"name":"Cube","id":0},{"name":"Capsule","id":1}]}
 
 
  • 1
  • 1

这就是你所保存的Json文件中的内容.


我打算上传都github,但是现在我github一直让更新,更新不成功,打不开啊!

留下地方吧!!

github一大早来更新,终于更新成功。 
** 
所以,源码地址:https://github.com/cartzhang/UnityJsonTest

快捷到达源码:Unity Json Test for 5.3

**

至此,Json文件的读写都搞定了.

更多

关于Json文件的使用,我打算尝试一个,能不能做个更好的配置,比如控制游戏的场景配置和游戏流程.打包后面不用修改,直接修改json 就可以创建一个完全不一样的游戏了. 
这样,是不是比较蠢呢!!可能会,比较复杂吧!! 
只个想法,若有兴趣,看看能不能实现一下.


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值