请先在Assets目录下面新建StreamingAssets文件夹
LitJson.dll放到Plugins下
下面DeviceInfo是一个设备信息类,大家可以根据自己需要进行拓展。
using LitJson;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.Networking;
public class Json_Manager : MonoBehaviour
{
private DeviceInfo m_devceInfo;
private string path = Application.streamingAssetsPath + "/DevInfo.json";
void Start()
{
//StartCoroutine(GetInfo(path));
}
private IEnumerator GetInfo(string uri)
{
//Uri m_uri = new Uri(uri);
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
// Request and wait for the desired page.
yield return webRequest.SendWebRequest();
string[] pages = uri.Split('/');
int page = pages.Length - 1;
if (webRequest.isNetworkError)
{
Debug.Log(pages[page] + ": Error: " + webRequest.error);
}
else
{
m_devceInfo = JsonMapper.ToObject<DeviceInfo>(webRequest.downloadHandler.text);
foreach (var item in m_devceInfo._设备List)
{
Debug.LogFormat("id : {0} name :{1}",item._id, item._name);
}
}
}
}
private IEnumerator GetDevInfo(string uri)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
yield return webRequest.SendWebRequest();
string[] pages = uri.Split('/');
int page = pages.Length - 1;
if (webRequest.isNetworkError)
{
Debug.Log(pages[page] + "Error : " + webRequest.error);
}
else
{
m_devceInfo = JsonMapper.ToObject<DeviceInfo>(webRequest.downloadHandler.text);
}
}
}
[ContextMenu("生成Json")]
public void 生成设备json()
{
DeviceInfo s = new DeviceInfo();
s._设备List = new List<DeviceInfo.DevItem>();
for (int i = 0; i < 100; i++)
{
DeviceInfo.DevItem temp = new DeviceInfo.DevItem(i, "devName" + i,"info" + i, "path" +i);
s._设备List.Add(temp);
}
Debug.LogError(s);
StringBuilder sb = new StringBuilder();
JsonWriter jr = new JsonWriter(sb);
jr.PrettyPrint = true; //设置为格式化模式,LitJson称其为PrettyPrint(美观的打印),在 Newtonsoft.Json里面则是 Formatting.Indented(锯齿状格式)
jr.IndentValue = 4; //缩进空格个数
JsonMapper.ToJson(s, jr);
Debug.LogError(Regex.Unescape(sb.ToString()));
File.WriteAllText(Application.streamingAssetsPath + "/DevInfo.json", Regex.Unescape(sb.ToString()));
}
}
DeviceInfo类如下
using System;
using System.Collections.Generic;
public class DeviceInfo
{
public DeviceInfo()
{
}
public DeviceInfo(List<DevItem> myDevList)
{
_设备List = myDevList ?? throw new ArgumentNullException(nameof(myDevList));
}
public List<DevItem> _设备List;
public class DevItem
{
public int _id;
public string _name;
public string _info;
public string _spriterPath;
public DevItem()
{
}
public DevItem(int id, string name, string info, string spriterPath)
{
_name = name ?? throw new ArgumentNullException(nameof(name));
_id = id;
_info = info ?? throw new ArgumentNullException(nameof(info));
_spriterPath = spriterPath ?? throw new ArgumentNullException(nameof(spriterPath));
}
}
}