using UnityEngine;
using System.Collections;
using LitJson;
using System.IO;
using System.Text;
public class Json : MonoBehaviour {
void Start () {
//WriteJson();
// ReadJson();
ReadJson_Two();
}
// Update is called once per frame
void Update () {
}
public void WriteJson() {
StringBuilder strB = new StringBuilder();
JsonWriter jsWriter = new JsonWriter(strB);
//所有的开始
jsWriter.WriteObjectStart();
jsWriter.WritePropertyName("Country");
jsWriter.Write("China");
jsWriter.WritePropertyName("Province");
//开始写省份数组
jsWriter.WriteArrayStart();
//数组的第一个元素的第一个元素
jsWriter.WriteObjectStart();
jsWriter.WritePropertyName("Name");
jsWriter.Write("LiaoNingSheng");
//数组的第一个元素的第二个元素
jsWriter.WritePropertyName("City");
jsWriter.Write("DaLian");
jsWriter.WriteObjectEnd();
//数组的第二个元素的第一个元素
jsWriter.WriteObjectStart();
jsWriter.WritePropertyName("Name");
jsWriter.Write("JiLingSheng");
//数组的第二个元素的第二个元素
jsWriter.WritePropertyName("City");
jsWriter.Write("ChangChun");
jsWriter.WriteObjectEnd();
//结束写省份数组
jsWriter.WriteArrayEnd();
jsWriter.WriteObjectEnd();
string path = Application.dataPath + "/lc.json";
//初始化一个
StreamWriter sw;
sw = File.CreateText(path);
//写入
sw.WriteLine(strB);
//关闭
sw.Close();
}
public void ReadJson()
{
string path = Application.dataPath + "/lc.json";
StreamReader sr = new StreamReader(path);
// SReader sr = new StringReader(path);//读
string str = sr.ReadToEnd();//读完
JsonData jd = JsonMapper.ToObject(str);
JsonData country = jd["Country"];
Debug.Log(country.ToString());
JsonData province = jd["Province"];
for (int i = 0; i < province.Count; i++)
{
Debug.Log(province[i]["Name"].ToString());
Debug.Log(province[i]["City"].ToString());
}
}
public void ReadJson_Two() {
string path = Application.dataPath + "/lc.json";
StreamReader sr = new StreamReader(path);
//StringReader sr = new StringReader(path);//读
string str = sr.ReadToEnd();//读完
JsonData jd = JsonMapper.ToObject(str);
JsonData country = jd["name"];
JsonData province = jd["province"];
JsonData cities = jd["cities"];
for (int i = 0; i < province.Count; i++)
{
Debug.Log(province[i]["name"].ToString());
for (int j = 0; j < province[i]["cities"]["city"].Count; j++)
{
Debug.Log(province[i]["cities"]["city"][j].ToString());
}
}
}
}
//可以时时更新
/*
FileInfoinfo = new FileInfo(path);
if(File.Exists(path))
{
File.Delete(path);
}
*/