unity——litjson


一、關於litjson
litjson是一個輕巧的cs讀寫json文件的開源庫。
 
二、簡單的讀取json例子:(win7、vs10的環境)
(1)litjson官網下載源碼,新建一個cs項目庫工程,將litjson源碼中的src文件夾里面的cs源文件添加到工程中進行編譯。
編譯前,將工程屬性中的NetFramework框架設置為3.5或者是2.0,因為unity的mono默認支持3.5或3.5以下的netframework版本,否則dll放入unity時會提示類似如下異常:
“Internal compiler error. See the console log for more information. output was:
Unhandled Exception: System.Reflection.ReflectionTypeLoadException: The classes in the module cannot be loaded.”
另外,litjson源碼中的benchmarks文件夾(生成dll時並不需要)里面的代碼是依賴newtonsoft.json的,其官網如下:
(2)編譯后會提示如下警告,你可以忽略它也可以干掉它。
“由於程序集沒有 CLSCompliant 特性,因此“LitJson.JsonWriter.Write(ulong)”不需要 CLSCompliant 特性"
參考:
(3)將dll導入Unity
方式一:Asset->Import New Asset,選擇剛編譯好的dll
方式二:在unity的Assets目錄創建一個Plugins文件夾(若已存在該文件夾,就不需要再創建了),dll須放在該文件下才能使用using加載。
(4)測試是否生效,測試代碼見附錄。
 
注意:
(1)在使用JsonMapper.ToObject<>時,模板與json表字段的名稱是一樣的。
(2)
若包含Dictionary結構,則key的類型必須是string,而不能是int類型(如需表示id等),否則無法正確解析!
若需要小數,要使用double類型,而不能使用float,可后期在代碼里再顯式轉換為float類型。
 
三、附錄:
test_litjson.json內容如下:

{
"TestString": "test_string",
"TestTable": {
"TestMember1": "test_member1"
},
"TestList": [
{
"Key": 1,
"Val": "a"
},
{
"Key": 2,
"Val": "b"
}
]
}

 
TestLitJson.cs的內容如下:
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using LitJson;
 
public class TestJsContext
{
public class JsTable
{
public string TestMember1 = string.Empty;
}
public class JsListElem
{
public int Key = 0;
public string Val = string.Empty;
}
public string TestString = string.Empty;
public TestJsContext.JsTable TestTable = new TestJsContext.JsTable();
public List<TestJsContext.JsListElem> TestList = new List<TestJsContext.JsListElem>();
}
 
public class TestLitJson : MonoBehaviour
{
[MenuItem("GameTools/Json/Test/LoadTestJson")]
public static void MenuEventHandler_LoadTestJson()
{
string testJsonFilePath = Application.dataPath + "/GRes/Test/test_litjson.json";
string jsonContext = System.IO.File.ReadAllText(testJsonFilePath);
TestJsContext customObj = JsonMapper.ToObject<TestJsContext>(jsonContext);
//if (JsonMapper.//HasInterpretError())
//{
// Debug.LogWarning(JsonMapper.GetInterpretError());
//}
if(null != jsonContext)
{
Debug.Log(string.Format("TestString:{0}", customObj.TestString));
Debug.Log(string.Format("TestTable.TestMember1:{0}", customObj.TestTable.TestMember1));
for(int i = 1; i < customObj.TestList.Count; ++ i)
{
Debug.Log(string.Format("TestList[{0}]:{1},{2}", i, customObj.TestList[i].Key, customObj.TestList[i].Val));
}
}
else
{
Debug.Log("jsonContext is null");
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM