原文内容来自:Read from and write to external .json files using JsonUtilities or LitJson
文件Unity 版本号5.3,使用时候Unity 版本号5.6
本文仅作分析,学习用途。
_3WriteJson_ObjectArray_LitJson
----------------------------------------------------------------------------------------------原代码+注释
// Transform objects to a JSON-formatted string and save it into a file.
// using LitJson
// storing nested objects in array
// creating {"highscore":[{"name":"MagicMike","scores":8828},{"name":"MadMax","scores":4711}]}
using UnityEngine;
using LitJson;
using System.IO;
using System.Collections.Generic;
public class _3WriteJson_ObjectArray_LitJson : MonoBehaviour {
void Start () {
/**
* 1. Create some nested objects in an array and store them into a JSON string
* 创建一些嵌套对象 到 一个数组中,并且 存储 这些对象 到JSON 字符串中
*/
//创建 一个内部对象 List 保存,用户的 名字 和 得分
List<InnerObjectData_LitJson> innerObjects_list = new List<InnerObjectData_LitJson> ();
innerObjects_list.Add(new InnerObjectData_LitJson ("MagicMike", 88289));//添加 玩家的 名字 和得分 到 innerObjects_list表中
innerObjects_list.Add(new InnerObjectData_LitJson ("MadMax", 47119));
InnerObjectData_LitJson[] innerObjects_array = innerObjects_list.ToArray();//转换为 数组
// 新的 主对象数据List Json 使得 内部对象数据LitJson 数组
//放入主对象数据List Json mainObject 中
MainObjectData_LitJson mainObject = new MainObjectData_LitJson (innerObjects_array);
JsonData jsonString = JsonMapper.ToJson (mainObject);//转换 主对象数据List Json mainObject 为JSONData jsonString
Debug.Log ("generated JsonString: "+ jsonString);//输出数据
// logs {"highscore":[{"name":"MagicMike","scores":8828},{"name":"MadMax","scores":4711}]}
/**
* 2. Save JSON-formatted string in text file
* 保存 JSON格式 的字符串 到Json_ObjectArray.json 文本中
*/
File.WriteAllText(Application.dataPath+"/Resources/Json_ObjectArray.json", jsonString.ToString());
}
}
public class MainObjectData_LitJson
{//主对象数据List Json,用于存储 最高得分
public InnerObjectData_LitJson [] highscore;
public MainObjectData_LitJson(InnerObjectData_LitJson [] highscore){
this.highscore = highscore;
}
}
public class InnerObjectData_LitJson
{//内部对象数据LitJson,用于存储 玩家 的 名字和得分
public string name;
public int scores;
public InnerObjectData_LitJson(string name, int scores){
this.name = name;
this.scores = scores;
}
}
----------------------------------------------------------------------------------------------代码图片
----------------------------------------------------------------------------------------------代码运行的结果
可以看到的是"highscore":[ 两个玩家 数据(名字、分数) ]的数据
----------------------------------------------------------------------------------------------