前面两篇文章已经介绍过了通过Excel配表生成类文件和Json文件,今天这篇文章将介绍最后一步,在项目中如何使用类文件和Json,获取到我们需要的数据。
因为本人项目中使用的第三方Json插件是Json.Net,所以后面示例代码中用到的都是Json.Net,Json.Net在前一篇文章《Json文件生成》中也有介绍过。话不多说马上开始吧。
/*Auto-create script.
* Don't Edit it. */
using System.Collections.Generic;
namespace Framework.Config
{
public class AccountConfig
{
/// <summary>id</summary>
public object id;
/// <summary>账号</summary>
public string account;
/// <summary>密码</summary>
public string password;
}
}
[
{
"id": 0,
"account": "chenzhijie",
"password": "123456"
},
{
"id": 1,
"account": "zhouchen",
"password": "654321"
},
{
"id": 2,
"account": "liangchong",
"password": "333333"
},
{
"id": 3,
"account": "zhangle",
"password": "444444"
}
]
上面就是通过Excel生成的类文件和Json文件,类文件和Json文件都被生成到项目工程下,所以可以在项目中使用和访问到。
using System.Collections.Generic;
using UnityEngine;
using Framework.Config;
using Newtonsoft.Json;
namespace Framework
{
public class Main : MonoBehaviour
{
private void Awake()
{
TextAsset textAsset = Resources.Load<TextAsset>("AccountConfig.json");
List<AccountConfig> accountConfigList = JsonConvert.DeserializeObject<List<AccountConfig>>(textAsset.text);
AccountConfig accountConfig = accountConfigList[0];
Debug.Log("AccountConfig id:" + accountConfig.id);
Debug.Log("AccountConfig account:" + accountConfig.account);
Debug.Log("AccountConfig password:" + accountConfig.password);
}
}
}
通过上面的代码可以看到,首先我们是通过Resources.Load方法读取到AccountConfig.json文件,然后通过JsonConvert.DeserializeObject方法反序列化成我们事先生成好的类,反序列化之后我们就可以正常的使用这个类对象了。
到这里《导表工具开发》的四篇文章就都介绍完了,希望对小伙伴们有帮助。