【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;

}

相关推荐
作孽就得先起床2 小时前
unity UnauthorizedAccessException: 拒绝访问路径
unity·游戏引擎
tealcwu4 小时前
【Unity踩坑】Unity项目提示文件合并有冲突
elasticsearch·unity·游戏引擎
tealcwu20 小时前
【Unity小技巧】如何将3D场景转换成2D场景
3d·unity·游戏引擎
全栈陈序员1 天前
用Rust和Bevy打造2D平台游戏原型
开发语言·rust·游戏引擎·游戏程序
鹿野素材屋1 天前
Unity模型中人形角色的嘴巴一直开着怎么办
unity
世洋Blog1 天前
Unity面经-List底层原理、如何基于数组、如何扩容、List存储泛型、List有关在内存中的结构
unity·面试·c#·list
神秘的土鸡1 天前
【CS创世SD NAND征文】为无人机打造可靠数据仓:工业级存储芯片CSNP32GCR01-AOW在飞控系统中的应用实践
嵌入式硬件·游戏引擎·无人机·cocos2d·雷龙
jtymyxmz2 天前
《Unity Shader》6.4.3 半兰伯特模型
unity·游戏引擎
AA陈超2 天前
ASC学习笔记0001:处理目标选择系统中当Actor拒绝目标确认时的调用
c++·笔记·学习·游戏·ue5·游戏引擎·虚幻
我的golang之路果然有问题2 天前
mac配置 unity+vscode的坑
开发语言·笔记·vscode·macos·unity·游戏引擎