在读取StreamingAssets目录下的json数据时,不知道是不是带着新手buff的原因,老是出现各种问题,读取不了文件,在安卓目录下找不到地址,解析不了json,最后还是使用www方式读取到文件
1、D_Text.json 内容, 在StreamingAssets 目录下
{ "ID": 3001001, "type": 1, "text": "\u60a8ID\u4e3a{0}\u7684{1}\u51fa\u552e\u6210\u529f\uff0c\u83b7\u5f97{2}\u9a91\u58eb\u5e01", "title": "\u51fa\u552e\u6210\u529f" }
2、转换成的类
[System.Serializable] public class D_Text { public int ID { get; set; } public int type { get; set; } public string text { get; set; } public string title { get; set; } }
3、
注意格式必须时“ANSI”不然在手机上读取不到
//读取StreamingAssets中的文件 参数 StreamingAssets下的路径 public string getTextForStreamingAssets(string path) { string localPath = ""; if (Application.platform == RuntimePlatform.Android) { localPath = Application.streamingAssetsPath + path; } else { localPath = "file:///" + Application.streamingAssetsPath + path; } WWW t_WWW = new WWW(localPath); //格式必须是"ANSI",不能是"UTF-8" if (t_WWW.error != null) { Debug.LogError("error : " + localPath); return ""; //读取文件出错 } while (!t_WWW.isDone) { } Debug.Log("t_WWW.text= " + t_WWW.text); return t_WWW.text; }
4、json解析
public D_Text LoadJsonD_Text() { string jsonStr = getTextForStreamingAssets("/D_Text.json"); if (jsonStr == null) { return null; } return JsonUtility.FromJson<D_Text>(json); }
5、如果遇到非标准化的json可采用JsonConvert 解析
例如:
{ "3001001": { "ID": 3001001, "type": 1, "text": "\u60a8ID\u4e3a{0}\u7684{1}\u51fa\u552e\u6210\u529f\uff0c\u83b7\u5f97{2}\u9a91\u58eb\u5e01", "title": "\u51fa\u552e\u6210\u529f" }, "3001002": { "ID": 3001002, "type": 1, "text": "\u60a8ID\u4e3a{0}s\u7684{1}\u51fa\u552e\u8d85\u65f6\uff0c\u5df2\u4e0b\u67b6", "title": "\u51fa\u552e\u8d85\u65f6" } }
Dictionary<int, D_Text> m_D_Text = new Dictionary<int, D_Text>(); //消息 public Dictionary<int, D_Text> LoadJsonD_Text() { if (m_D_Text.Count > 0) return m_D_Text; string jsonStr = getTextForStreamingAssets("/D_Text.json"); if (jsonStr == null) { return null; } string json = jsonStr; if (json.Length > 2) { int j = 0; //遇到一次json前面莫名奇妙多了个字符,但又不是空字符,while做的一些特殊处理,可不用 while (json[0] != '{') { Debug.LogError("D_Sell.py.datas.json is not json" + json[0]); json.Remove(0); j++; if (j > 10) { break; } } JObject obj = JObject.Parse(json); foreach (var inter in obj) { D_Text kky = JsonConvert.DeserializeObject<D_Text>(inter.Value.ToString()); m_D_Text.Add(kky.ID, kky); } } return m_D_Text; }
Newtonsoft.Json.dll 下载
链接:
https://pan.baidu.com/s/1WWrZmKNas811w6zWt9E3Xg 密码:lc1o