【Unity&JSON】JsonUtility的多对象读写(4)

来源:互联网 发布:上海市行知中学校徽 编辑:程序博客网 时间:2024/06/12 08:17

原文内容来自:Read from and write to external .json files using JsonUtilities or LitJson

文件Unity 版本号5.3,使用时候Unity 版本号5.6

文件分流unity-json-master

本文仅作分析,学习用途。

类似下面这样,//* 这样的表示和 LitJson 对应 的代码 相同。

//* 的 分数 +1

通过注释来区别 。主要用于 表示 在 代码中 可以 改变 的数据。

someList.Add (createSubObject ("Amazing Angus6", 64546));

原代码,无注释。

someList.Add (createSubObject ("Amazing Angus", 6454));


_4Update_ObjectArray_JsonUtility
----------------------------------------------------------------------------------------------原代码+注释

// Reading an array with nested object stored in a JSON-formatted text file. Changing objects and adding more objects
// using JsonUtility
// At start: {"highscore":[{"name":"BadBoy","scores":4711}]}
// After step 5: {"highscore":[{"name":"BadBoy","scores":4711},{"name":"MagicMike","scores":8828}]}
// After step 7: {"highscore":[{"name":"BadBoy","scores":4712},{"name":"MadMax","scores":1234},{"name":"Amazing Angus","scores":6454},{"name":"Good Guys","scores":1936}]}

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

public class _4Update_ObjectArray_JsonUtility : MonoBehaviour {
    void Start () {

        /**
         * 1. Fetch text from file * 从文件中取出 text 文本
         */

        string jsonString = File.ReadAllText (Application.dataPath + "/Resources/Json_UpdateObjectArray.json");
        Debug.Log ("JSON-String before: " + jsonString);
        // logs {"highscore":[{"name":"BadBoy","scores":4711}]}

        /**
         * 2. Transform JSON formatted text into object
         * * 转换 JSON 格式 文本 成为 JSONDATA 对象 myObject。 文本-》对象
         */

        MainObjectData_upd_JsonUtility mainObject = JsonUtility.FromJson<MainObjectData_upd_JsonUtility> (jsonString);
        Debug.Log("Size of array before: " + mainObject.highscore.Length); // 1

        List<string> name_list = new List<string> ();//* 专门存放 名字 的字符串List
        List<int> scores_list = new List<int> ();//* 专门存放 分数 的整型List
        //* 遍历每一个 "highscore"
        for (int i=0; i < mainObject.highscore.Length; i++) {
            name_list.Add(mainObject.highscore[i].name.ToString());//* 找到myObject中的"highscore"中的"name" 数据转换为字符串 并保存
            scores_list.Add(int.Parse(mainObject.highscore[i].scores.ToString()));//* 找到myObject中的"highscore"中的"scores" 数据转换为字符串 并保存
        }

        /**
         * 3. Enlarge the JSON Object * 放大 JSON 对象
         */

        name_list.Add ("MadMax6");//* 在 名字 列表 中添加一个名字
        scores_list.Add (12346);//* 在 分数 列表 中添加一个分数

        /**
         * 4. Change entries in JSON object
         * BadBoy bekommt einen Extrapunkt
         */

        int position=-1;
        for (int i = 0; i < name_list.Count; i++)
        {//* 遍历 每个 名字 列表的名字
            if (name_list [i] == "BadBoy")
            {//* 找到 名字为 "BadBoy" 的 数字索引
                position = i;//* 获得 "BadBoy" 的  位置  数字索引
                break;
            }
        }
        if (position > -1)//* "BadBoy" 的  位置  数字索引
            scores_list [position] += 1;//* 的 分数 +1

        /**
         * 5. Create some nested objects in an array again and store them back into a JSON string
         * * 创建一些 嵌套对象 到 数组中 ,并且 使得这些 数据 存储 为JSON 字符串
         */
        //* 定义并赋值一个空的   内部对象数据LitJson,用于存储 玩家 的 名字和得分
        List<InnerObjectData_upd_JsonUtility> innerObjects_list = new List<InnerObjectData_upd_JsonUtility> ();
        for (int i = 0; i < name_list.Count; i++) {
            InnerObjectData_upd_JsonUtility myInnerObject = new  InnerObjectData_upd_JsonUtility();//* 在 内部对象表 中添加 内部对象数据(名字表,得分表)
            myInnerObject.name = name_list[i];
            myInnerObject.scores = scores_list[i];
            innerObjects_list.Add (myInnerObject);//内部对象 表 中 添加 myInnerObject
        }

        mainObject.highscore = innerObjects_list.ToArray();

        jsonString = JsonUtility.ToJson(mainObject);//* 把 mainObject 从对象 转换  为JSON格式
        Debug.Log ("JSON-String thereafter: " + jsonString);
        // logs {"highscore":[{"name":"BadBoy","scores":4711},{"name":"MagicMike","scores":8828}]}
        Debug.Log("Size of array thereafter: " + mainObject.highscore.Length); // 2

        /**
         * 6. Save JSON-formatted string in text file
         */

        //File.WriteAllText(Application.dataPath+"/Resources/Json_UpdateObjectArray.json", jsonString.ToString());

        /**
         * 7. Quickly adding more objects without touching existing contents, thus faster (not possible with LitJson)
         */
        // 把 jsonString 从 JSON格式 转换 为对象
        mainObject = JsonUtility.FromJson<MainObjectData_upd_JsonUtility> (jsonString);
        List<InnerObjectData_upd_JsonUtility> someList = new List<InnerObjectData_upd_JsonUtility>(mainObject.highscore);//新建一个 排名榜
        //在排名榜中 添加 (新建 名字,分数)
        someList.Add (createSubObject ("Amazing Angus6", 64546));
        someList.Add (createSubObject ("Good Guys6", 19366));

        mainObject.highscore = someList.ToArray();//

        jsonString = JsonUtility.ToJson(mainObject);//把对象 转换 为JSON格式
        Debug.Log ("Quickly added one more object without analyzing contents: " + jsonString);
        // logs {"highscore":[{"name":"BadBoy","scores":4712},{"name":"MadMax","scores":1234},{"name":"Amazing Angus","scores":6454},{"name":"Good Guys","scores":1936}]}
        Debug.Log("Size of array thereafter: " + mainObject.highscore.Length); // 4

        /**
         * 8. Save JSON-formatted string in text file
         */

        //File.WriteAllText(Application.dataPath+"/Resources/Json_UpdateObjectArray.json", jsonString.ToString());
    }
    //一个 InnerObjectData_upd_JsonUtility 类型的 createSubObject 公共函数
    public InnerObjectData_upd_JsonUtility createSubObject(string name, int scores){
        InnerObjectData_upd_JsonUtility myInnerObject = new  InnerObjectData_upd_JsonUtility();
        myInnerObject.name = name;
        myInnerObject.scores = scores;
        return myInnerObject;
    }
}

[Serializable]//UNITY 自带的序列化
public class MainObjectData_upd_JsonUtility
{//主对象数据List Json,用于存储 最高得分
    public InnerObjectData_upd_JsonUtility [] highscore;
}

[Serializable]//UNITY 自带的序列化
public class InnerObjectData_upd_JsonUtility
{//内部对象数据LitJson,用于存储 玩家 的 名字和得分
    public string name;
    public int scores;
}

----------------------------------------------------------------------------------------------代码图片





----------------------------------------------------------------------------------------------代码运行的结果



----------------------------------------------------------------------------------------------逻辑图


----------------------------------------------------------------------------------------------

0 0
原创粉丝点击