using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Test
{
public class TestUnityJson : MonoBehaviour {
void Start () {
Hero heroObj=new Hero();
heroObj.Name = "郭靖";
heroObj.MyLevel = new Level() {HeroLevel = 800};
//相当于如下写法
//Level lev=new Level();
//lev.HeroLevel = 800;
//heroObj.MyLevel = lev;
//方法1: Json 序列化工作(对象--> Json)
string strHeroInfo = JsonUtility.ToJson(heroObj);
Debug.Log("测试1: 得到的序列化后的字符串="+strHeroInfo);
//方法2: 反序列化(Json文件--> 对象)
Hero heroInfo2 = JsonUtility.FromJson<Hero>(strHeroInfo);
Debug.Log("测试2:得到反序列化对象数值,名称: "+heroInfo2.Name+" 等级: "+heroInfo2.MyLevel.HeroLevel);
//方法3: 测试覆盖反序列化。
Hero hero=new Hero();
hero.Name = "杨过";
hero.MyLevel = new Level() {HeroLevel = 500};
//Json 序列化
string heroInfo3 = JsonUtility.ToJson(hero);
//测试覆盖反序列化
JsonUtility.FromJsonOverwrite(heroInfo3, heroObj);
Debug.Log("测试3, 得到再次反序列化覆盖的对象信息,名称: "+heroObj.Name+" 等级: "+heroObj.MyLevel.HeroLevel);
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Test
{
[Serializable]
public class Hero
{
//字段必须和Json里面的相同
//名称
public string Name;
//等级
public Level MyLevel;
}
}
对于Unity中Resource 目录下的Json 文件的解析
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Test
{
public class TestUnityJson2 : MonoBehaviour {
void Start ()
{
//提取文件,得到字符串数据
TextAsset TaObj=Resources.Load<TextAsset>("People");
//反序列化 文件-->对象
PersonInfo perInfo=JsonUtility.FromJson<PersonInfo>(TaObj.text);
//显示对象中数据
foreach (People per in perInfo.People)
{
Debug.Log(" ");
Debug.Log(string.Format("name={0},Age={1}",per.Name,per.Age));
}
}
}
}
//实体类集合
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
[Serializable]
public class PersonInfo
{
//字段People 必须和Json里面的People相同
public List<People> People;
}
}
People.Json
{
"People":
[
{"Name":"张三","Age":20},
{"Name":"李四","Age":30},
{"Name":"王五","Age":40}
]
}