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

}

相关推荐
Magnum Lehar9 小时前
wpf3d游戏引擎ControlTemplate.xaml.cs文件实现
游戏引擎·wpf
留待舞人归9 小时前
【Unity3D优化】优化多语言字体包大小
游戏·unity·游戏引擎·unity3d·优化
wsdchong之小马过河10 小时前
2025虚幻引擎一般用什么模型格式
游戏引擎·虚幻
技术小甜甜17 小时前
[Blender] 高质量材质推荐第四弹:25-30号精选纹理资源详解
blender·游戏开发·材质·建模·资源
Magnum Lehar17 小时前
wpf游戏引擎前端的Transform.cs实现
前端·游戏引擎·wpf
Magnum Lehar20 小时前
wpf3d游戏引擎前端ControlTemplate实现
前端·游戏引擎·wpf
97650333521 小时前
iOS 审核 cocos 4.3a【苹果机审的“分层阈值”设计】
flutter·游戏·unity·ios
EQ-雪梨蛋花汤1 天前
【Unity笔记】Unity Animation组件使用详解:Play方法重载与动画播放控制
笔记·unity·游戏引擎
AgilityBaby1 天前
Untiy打包安卓踩坑
android·笔记·学习·unity·游戏引擎
菌菌巧乐兹2 天前
Unity | AmplifyShaderEditor插件基础(第九集:旗子进阶版)
unity·游戏引擎