unity中解析json文件
文件管理类:
using UnityEngine;
using System.Collections;
using System.IO;
public class FileManger {
private static FileManger _instance;
public static FileManger getInstance(){
if (_instance == null) {
_instance = new FileManger ();
}
return _instance;
}
private FileManger(){
}
public void createOrwritrConfigFile(string path,string name,string info){
File.WriteAllText (path+"//"+name,info);
}
public void DeleteFile(string path,string name){
string delPath = path + "//" + name;
File.Delete (delPath);
}
public string loadFile(string path,string name){
string readPath = path + "//" + name;
FileInfo info = new FileInfo (readPath);
if (info.Exists) {
string text = File.ReadAllText (readPath);
return text;
} else {
return null;
}
}
}
加载文件:
引入第三方文件LJR
using LitJson;
void testFileCreate(){
string path = Application.dataPath;//json文件路径
string fileName = "demo1.json";//文件名
string jsonStr = FileManger.getInstance ().loadFile (path, fileName);
//从文件中读取信息并存储在jsonStr中
JsonData newData = JsonMapper.ToObject (jsonStr);//转换字符串类型为字典
JsonData levels = newData ["Levels"];//寻找’key‘为‘Levels’的值对应的‘value’值
Debug.LogFormat ("{0},{1},{2}",levels[0]["name"],levels[0]["star"],levels[0]["lock"]);
//格式化输出
}
json文件内容
{
"Levels":[
{"name":"level1","star":0,"lock":0},
{"name":"level2","star":0,"lock":0},
{"name":"level3","star":0,"lock":0},
{"name":"level4","star":0,"lock":0},
{"name":"level5","star":0,"lock":0},
{"name":"level6","star":0,"lock":0},
{"name":"level7","star":0,"lock":0},
{"name":"level8","star":0,"lock":0}]
}
写入Json文件,更改Json文件内容,重新创建同名Json文件覆盖之前的json文件
<pre name="code" class="csharp"> levels [0] ["star"] = 3;
string json = JsonMapper.ToJson (newData);
FileManger.getInstance ().createOrwritrConfigFile (path, fileName, json);
Json在线校验格式化工具:http://www.bejson.com/