一、关于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");
}
}
}