原文内容来自:Read from and write to external .json files using JsonUtilities or LitJson
文件Unity 版本号5.3,使用时候Unity 版本号5.6
本文仅作分析,学习用途。
_4Update_ObjectArray_LitJson
----------------------------------------------------------------------------------------------原代码+注释
// Reading an array with nested object stored in a JSON-formatted text file. Changing objects and adding more objects
// using LitJson
// At start: {"highscore":[{"name":"BadBoy","scores":4711}]}
// After step 5: {"highscore":[{"name":"BadBoy","scores":4712},{"name":"MadMax","scores":1234}]}
using UnityEngine;
using LitJson;
using System.IO;
using System.Collections.Generic;
public class _4Update_ObjectArray_LitJson : 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
*/
JsonData myObject = JsonMapper.ToObject (jsonString);
Debug.Log("Size of array before: " + myObject["highscore"].Count); // 1
List<string> name_list = new List<string> ();//专门存放 名字 的字符串List
List<int> scores_list = new List<int> ();//专门存放 分数 的整型List
//遍历每一个 "highscore"
for (int i=0; i < myObject ["highscore"].Count; i++) {
name_list.Add(myObject["highscore"][i]["name"].ToString());//找到myObject中的"highscore"中的"name" 数据转换为字符串 并保存
scores_list.Add(int.Parse(myObject["highscore"][i]["scores"].ToString()));//找到myObject中的"highscore"中的"scores" 数据转换为字符串 并保存
}
/**
* 3. Enlarge the JSON Object 放大 JSON 对象
*/
name_list.Add ("MadMax");//在 名字 列表 中添加一个名字
scores_list.Add (1234);//在 分数 列表 中添加一个分数
/**
* 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_LitJson> innerObjects_list = new List<InnerObjectData_upd_LitJson> ();
for (int i = 0; i < name_list.Count; i++) {//遍历 每一个 名字表
innerObjects_list.Add (new InnerObjectData_upd_LitJson (name_list [i], scores_list [i]));
//在 内部对象表 中添加 内部对象数据(名字表,得分表)
}
//把 list 表格 转换 为 array 数组
//定义并赋值一个 主对象数据List Json,用于存储 最高得分
InnerObjectData_upd_LitJson[] innerObjects_array = innerObjects_list.ToArray();
//定义一个 主对象数据List Json, 其值 为 内部对象数组
MainObjectData_upd_LitJson_new mainObject = new MainObjectData_upd_LitJson_new (innerObjects_array);
jsonString = JsonMapper.ToJson (mainObject);//把 mainObject 从对象 转换 为JSON格式
Debug.Log ("JSON-String thereafter: " + jsonString);
// logs {"highscore":[{"name":"BadBoy","scores":4712},{"name":"MadMax","scores":1234}]}
myObject = JsonMapper.ToObject (jsonString);//把 mainObject 从JSON字符串格式 转换 对象
Debug.Log("Size of array thereafter: " + myObject["highscore"].Count); // 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 is NOT possible with LitJson, however with JsonUtility.
*
* Reason: Using JsonUtility, you work with instances of the classes MainObjectData and SubObjectData for both
* encoding and decoding a JSON-formatted string. When decoding the string you get an array of the type InnerObjectData.
* Thus you can simply add more instances of the class InnerObjectData to this list/array. So you needn't analyse the
* whole data structure when you simply want to add more objects without changing the rest.
* Using LitJson you only need the instances of the classes MainObjectData and SubObjectData for encoding the
* JSON-formatted string, but NOT for decoding. When decoding you don't get an array of the type InnerObjectData.
* You get an object of the type LitJson.JsonData. It's not possible to add instances of InnerObjectData to it.
* At best, you get a useless string like this: {"highscore":[{"name":"BadBoy","scores":4711}"{\"name\":\"MagicMike\",\"scores\":8828}"]}
*/
}
}
public class MainObjectData_upd_LitJson_new
{//主对象数据List Json,用于存储 最高得分
public InnerObjectData_upd_LitJson [] highscore;
public MainObjectData_upd_LitJson_new(InnerObjectData_upd_LitJson [] highscore){
this.highscore = highscore;
}
}
public class InnerObjectData_upd_LitJson
{//内部对象数据LitJson,用于存储 玩家 的 名字和得分
public string name;
public int scores;
public InnerObjectData_upd_LitJson(string name, int scores){
this.name = name;
this.scores = scores;
}
}
----------------------------------------------------------------------------------------------代码图片
----------------------------------------------------------------------------------------------代码运行的结果
----------------------------------------------------------------------------------------------