【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_Array[i]["n1"]);

Debug.Log("n2 =" + jsonDate_Array[i]["n2"]);

}

}

}

Serializable

public class PersonOfJson

{

public string name;

public int age;

}

Serializable

public class PersonsOfJson

{

public List<PersonOfJson> personOfJsonList;

public int id;

}

相关推荐
平行云PVT2 小时前
实时云渲染解决UE5 像素流插件迁移及传输数据受限问题
unity·ue5·xr·实时云渲染·云桌面·像素流·云推流
熬夜敲代码的小N5 小时前
Unity WebRequest高级操作:构建高效稳定的网络通信模块
android·数据结构·unity·游戏引擎
萘柰奈5 小时前
Unity【小问题】----URP项目中加载AssetBundle中的预设体即使加载了依赖的材质依然是紫色的问题
unity·游戏引擎·材质
wonder135796 小时前
UGUI合批分析和优化方法整理
unity·ugui
海中有金8 小时前
Unreal Engine 线程模型深度解析[2]
人工智能·游戏引擎·虚幻
海中有金8 小时前
Unreal Engine 内存池浅谈[11]——总结篇
游戏引擎·虚幻
wonder135798 小时前
UGUI鼠标点击到按钮响应流程的源码分析
unity·ugui
SmalBox9 小时前
【URP】Unity[内置Shader]粒子光照ParticlesLit
unity3d·游戏开发·图形学
熊猫悟道1 天前
Unity shader 之,Shader内部时间离散处理
unity·游戏引擎·材质·着色器
PA_1 天前
unity Component-Based Architecture游戏框架
游戏·unity·游戏引擎