目前主流的輕量級數據交換格式非Json和xml莫屬,這裏說下利用dotnet版本Newtonsoft.Json.dll解析Json數據,xml數據可直接調用dotnet方法讀寫操作。
廢話不多說上代碼,一瞧便知。
1、需要解析的Json文件,這裏命名爲Test_1130.json:
{
"整形": 100,
"整形1": 200,
"整形2": 300,
"字符串": "string value",
"布爾值": "bool value",
"整形數組": [111,
222,
333],
"Json對象數組": [{
"整形元素": 9999,
"字符串元素": "string value"
}]
}
2、parseJosn.ms解析的maxscript代碼。
JsonDllPath = @"G:\CSDN\ParseJson\Newtonsoft.Json.dll"
JsonFilePath = @"G:\CSDN\ParseJson\Test_1130.json"
-- 讀取本地Json文件到字符變量
JsonString = ""
JsonFile = openFile JsonFilePath
while not eof JsonFile do
(
JsonString += readchar JsonFile
)
close JsonFile
-- 加載模塊
(dotnetClass "System.Reflection.assembly").Load ((dotnetClass "System.IO.File").ReadAllBytes(JsonDllPath))
-- 解析Json格式的字符
LinqJsonObj = (dotNetObject "Newtonsoft.Json.Linq.JObject").parse JsonString
-- 輸出對象的值
OutValue = (LinqJsonObj.GetValue "整形").Value
-- 如果是整形對象輸出需要把Integer64類型轉化爲Integer
format "\n整形:%\n" (OutValue as Integer)
-- print (OutValue as Integer)
-- 整形
-- print ((LinqJsonObj.GetValue "整形1").Value as Integer)
format "\n整形1:%\n" ((LinqJsonObj.GetValue "整形1").Value as Integer)
-- print ((LinqJsonObj.GetValue "整形2").Value as Integer)
format "\n整形2:%\n" ((LinqJsonObj.GetValue "整形2").Value as Integer)
-- 字符串
-- print (LinqJsonObj.GetValue "字符串").Value
format "\n字符串:%\n" (LinqJsonObj.GetValue "字符串").Value
-- 布爾
-- print (LinqJsonObj.GetValue "布爾值").Value
format "\n布爾值:%\n" (LinqJsonObj.GetValue "布爾值").Value
-- 整形數組
TestArray = (LinqJsonObj.GetValue "整形數組")
TestArray.Count --數組數量
for Index = 0 to (TestArray.Count - 1) do
(
-- print (TestArray.Item[Index].Value as Integer)
format "\n整形數組%:%\n" Index (TestArray.Item[Index].Value as Integer)
)
-- Json對象數組
TestJsonObjArray = (LinqJsonObj.GetValue "Json對象數組")
for Index = 0 to (TestJsonObjArray.Count - 1) do
(
-- print ((TestJsonObjArray.Item[Index].GetValue "整形元素").Value as Integer)
format "\n整形元素:%\n" ((TestJsonObjArray.Item[Index].GetValue "整形元素").Value as Integer)
-- print (TestJsonObjArray.Item[Index].GetValue "字符串元素").Value
format "\n字符串元素:%\n" (TestJsonObjArray.Item[Index].GetValue "字符串元素").Value
)
源代碼和相關文件:http://u.163.com/qfG13x1y 提取碼: EArxeSmr