原文内容来自:Read from and write to external .json files using JsonUtilities or LitJson
文件Unity 版本号5.3,使用时候Unity 版本号5.6
本文仅作分析,学习用途。
_1WriteJSON_basic_LitJson
----------------------------------------------------------------------------------------------原代码+注释
// Transform objects to a JSON-formatted string and save it into a file.
// using LitJson
// basic - without Object arrays
// creating {"name":"Fabi","level":4711,"tags":["Beginner","Fast"]}
using UnityEngine;
using LitJson;
using System.IO;
using System.Collections.Generic;
public class _1WriteJSON_basic_LitJson : MonoBehaviour {
void Start () {
/**
* 1. Create some objects and store them into a JSON string
*/
List<string> tags =new List<string>();//一个 string类型的List 名字为 tags 为一个新的 string类型的List
tags.Add ("Beginner1");//添加 “Beginner” 到 这个 名字为 tags 的 string类型的List
tags.Add ("Fast1");//添加 “Fast” 到 这个 名字为 tags 的 string类型的List
string [] tags_array = tags.ToArray();
//定义一个 string字符串 数组 名字叫 tags_array ,使得 string类型的List tags通过 ToArray转换成 字符串数组
ObjectData_LitJson mainObject = new ObjectData_LitJson ("Fabi2", 47112, tags_array);
//新建一个 ObjectData_LitJson 类型 名字为 mainObject 的变量。其成员 变量 的值为("Fabi", 4711, tags_array)
//定义一个 JsonData 名字为generatedJsonString
JsonData generatedJsonString = JsonMapper.ToJson (mainObject);//使用 JsonMapper.ToJson 转换 类型变量 为数据
Debug.Log (generatedJsonString);//显示数组
// logs {"name":"Fabi","level":4711,"tags":["Beginner","Fast"]}
/**
* 2. Save JSON-formatted string in text file
*/
//保存 数据 到 。。。 文件
File.WriteAllText(Application.dataPath+"/Resources/Json_basic.json", generatedJsonString.ToString());
}
}
//ObjectData_LitJson 类,用于存放 成员 变量。 名字、等级、标签。
//这个ObjectData_LitJson 类,有一个公共函数 ObjectData_LitJson(string name, int level, string[] tags)
//使得ObjectData_LitJson 类的成员 变量 = 形参传递 的参数。
public class ObjectData_LitJson{
public string name;
public int level;
public string [] tags;
public ObjectData_LitJson(string name, int level, string[] tags){
this.name = name;
this.level = level;
this.tags = tags;
}
}
----------------------------------------------------------------------------------------------代码图片
----------------------------------------------------------------------------------------------代码运行的结果
----------------------------------------------------------------------------------------------
参考资料:
1.
2.
3.