unity对Json的操作有两种方式
- LitJson
- JsonUtility
JsonUtility
[Serializable]
public class Person{
public string name;
public int age;
}
public class Persons{
public Person[] persons;
}
public class JsonUtilityDemo:MonoBehaviour{
void Start(){
//使用代码生成一个json
//{'name':'李逍遥','age':25}
Person p1 = new Person();
p1.name = "李逍遥";
p1.age = 25;
string jsonStr = JsonUtility.ToJson(p1);
//Debug.Log(jsonStr);
//{'persons':[{'name':'李逍遥','age':25},{'name':'王小虎','age':7}]}
Person p2 = new Person();
p1.name = "王小虎";
p1.age = 7;
Person[] ps = new Person[]{p1,p2};
Persons persons = new Persons();
persons.persons = ps;
string jsonStr = JsonUtility.ToJson(persons);
//Debug.Log(jsonStr);
//解析Json
//{'persons':[{'name':'李逍遥','age':25},{'name':'王小虎','age':7}]}
Persons newPersons = JsonUtility.FromJson<Persons>(jsonStr);
Debug.Log(newPersons.persons[0].name);
}
}