unity解析json数据/文件


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/
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值