{}对象
[]数组
Json操作:两种方式 LitJson \ JsonUtility
1.JsonUtility创建json
引入Using System;命名空间
将类序列号,json和类相互转换,添加[Serializable]
[Serializable]
public class Person{
public string name;
public int age;
}
[Serializable]
public class Persons{
public Person[] persons;
}
使用代码方式创建一个json
//{‘name’:’李逍遥’,age”:25}
Person p1 = new Person();
p1.name=”李逍遥”;
p1.age = 25;
//转成json字符串
string jsonStr = JsonUtility.ToJson(p1);
//{‘persons’:[{‘name’:’李逍遥’,age”:25},{‘name’:’王小虎’,age”:25}]}
Person p2 = new Person();
p2.name = “王小虎”;
p2.age = 7;
Person[] ps=new Person[]{p1,p2};
Persons persons = new Persons();
persons.persons=ps;
jsonStr =JsonUtility.ToJson(persons);
//jsonStr ={‘persons’:[{‘name’:’李逍遥’,age”:25},{‘name’:’王小虎’,age”:25}]};
2.JsonUtility解析json
Persons newPersons= JsonUtility.FromJson(jsonStr);
Debug.Log(newPersons.persons[0].name);//李逍遥
3. LitJson 创建json
1.在网上下载Litjson.dll文件,导入unity中,必须放在Plugins文件夹中。
2.在脚本中添加using litJson;命名空间
//{‘heros’:[{‘name’:’超人’,’power’:90},{‘name’:’蝙蝠侠’,’power’:80}]}
JsonData herosJd=new JsonData ();//{}
JsonData herosJd1=new JsonData ();//{}
herosJd1[“name”]=”超人”;
herosJd1[“power”]=90;
JsonData herosJd2=new JsonData ();
herosJd2[“name”]=”蝙蝠侠”;
herosJd2[“power”]=80;
JsonData heros=new JsonData ();//[]
heros.SetJsonType(JsonType.Array);
heros.Add(herosJd1);
heros.Add(herosJd2);
herosJd[“heros”] = heros;
Debug.log(herosJd.ToJson());
4.LitJson 解析json
string jsonStr=”{‘heros’:[{‘name’:’超人’,’power’:90},{‘name’:’蝙蝠侠’,’power’:80}]}”;
JsonData herosJd=JsonMapper.ToObject(jsonStr);
JsonData heros=herosJd[“heros”];//[]
foreach(JsonData heroJd in heros)
{
Debug.log(heroJd[“name”].ToString());
Debug.log((int)heroJd[“power”]);
}