【Unity】使用LitJson保存和读取数据的例子

LitJson 是一个轻量级的 JSON 解析和生成库,广泛应用于 .NET 环境中。

优点:轻量级,易用,性能优秀,支持LINQ和自定义对象的序列化和反序列化。

public class LitJsonTest : MonoBehaviour

{

// Start is called before the first frame update

void Start()

{

PersonOfJson personOfJson1 = new();

personOfJson1.name = "keixo";

personOfJson1.age = 19;

//将数据转为字符串

string jsonStr1 = JsonMapper.ToJson(personOfJson1);

Debug.Log(jsonStr1);

//将字符串转为对象

PersonOfJson personOfJson4 = JsonMapper.ToObject<PersonOfJson>(jsonStr1);

//设有json数据

string jsonStr2 = @"{""name"" : ""zhaoxi"", ""age"" : 23 }";

PersonOfJson personOfJson5 = JsonMapper.ToObject<PersonOfJson>(jsonStr2);

Debug.Log(personOfJson5.name);

string jsonStr3 = @"

{

""name"" : ""alex"",

""id"" : 131231232,

""1"":[

{

""n1"" : ""n1"",

""n2"" : 1

},

{

""n1"" : ""n11"",

""n2"" : 2

}

]

}";

//可以把每个键值对都看成JsonData对象进行使用

JsonData jsonData = JsonMapper.ToObject(jsonStr3);

Debug.Log(jsonData"name");//alex

Debug.Log(jsonData"id");//131231232

JsonData jsonDate_Array = jsonData"1";

//遍历数组

for(int i = 0; i < jsonDate_Array.Count; i ++)

{

Debug.Log("n1 =" + jsonDate_Arrayi"n1");

Debug.Log("n2 =" + jsonDate_Arrayi"n2");

}

}

}

Serializable

public class PersonOfJson

{

public string name;

public int age;

}

Serializable

public class PersonsOfJson

{

public List<PersonOfJson> personOfJsonList;

public int id;

}

相关推荐
xcLeigh10 小时前
Unity基础:C#脚本的创建与挂载——让你的游戏物体活起来
游戏·unity·c#·教程
SmalBox16 小时前
【节点】[Keyword节点]原理解析与实际应用
unity3d·游戏开发·图形学
nujnewnehc19 小时前
游戏辅助后续之yolo
游戏·游戏开发
DaLiangChen1 天前
Vuforia 地面识别案例
unity·ar
江畔柳前堤2 天前
YOLO 目标检测全流程深度剖析
人工智能·yolo·目标检测·计算机视觉·unity·面试·vllm
魔术师Dix2 天前
一个轮子:Luban Skill 制作演示
游戏·unity·ai编程
SmalBox2 天前
【节点】[GetLocalVariable节点]原理解析与实际应用
unity3d·游戏开发·图形学
UWA2 天前
隐藏视频变“常驻刺客”,VideoPlayer与“N/A”纹理该怎么查
人工智能·性能优化·音视频·memory·cpu·游戏开发
xcLeigh2 天前
Unity基础:Light灯光组件入门——Directional Light、Point Light与Spotlight
unity·游戏引擎·教程