程序篇02:Unity数据序列化之Json - kudan-game/ArtArtist-Repo GitHub Wiki
更多示例介绍:https://zhuanlan.zhihu.com/p/60793039
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;//引入系统命名空间
[Serializable]//可序列化标识
public class Person
{
public string Name;
public int Age;
public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
}
[Serializable]
public class Persons
{
public Person[] persons;
public Persons(Person[] p)
{
this.persons = p;
}
}
public class TestSaveJson : MonoBehaviour
{
void Start()
{
JsonTest();
}
public void JsonTest()
{
//创建json
Person p1 = new Person("李逍遥", 25);
Person p2 = new Person("王小虎", 30);
string p1JsonStr = JsonUtility.ToJson(p1);
string p2JsonStr = JsonUtility.ToJson(p2);
Debug.Log(p1JsonStr);
Debug.Log(p2JsonStr);
//创建json数组
Person[] ps = new Person[] { p1, p2 };
Persons p3 = new Persons(ps);
string p3JsonStr = JsonUtility.ToJson(p3);
Debug.Log(p3JsonStr);
//解析json字符串
Person p = JsonUtility.FromJson<Person>(p2JsonStr);
Debug.Log("第二个人的名字:"+ p.Name);
//解析json数组字符串
Persons s = JsonUtility.FromJson<Persons>(p3JsonStr);
Debug.Log("第一个人的名字:"+ s.persons[0].Name);
}
}
运行结果如下: