- 一般情况下Json数据格式都是如下的字符串:
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
]
}
- 而在使用WebSocket进行通讯的过程中,后端方面我想自己组装一个Json数据给我前端使用,前端是Unity 3D客户端,解析Json数据的插件使用的是UnityLitJson,用这个插件所踩下的坑不计其数,最后我还是自己基于C#重新基写了一套类似的用于Unity 3D的Json字符串解析库,至少我自己用起来比较方便,不会出现莫名其妙的问题。先不说自己的库,这里就讲讲UnityLitJson这个库对于数据格式的苛刻要求,它必须接收如下这种格式,才能够解析出来:
{"ChatType":"LongChat","UserState":"Online","CallingState":"Leisure","Msg":"Other"}
- 后端因为使用的基于Typescript的Node.js写的,在组装字符串以形成字符串的时候需要在拼接的字符串上也要加上双引号,详情如下(注意ES6字符串符号语法内部的那些双引号):
function DataStruct(chatType: ChatType, userState: UserState, callingState: CallingState, msg: Msg) {
const result: string = `{
"ChatType": "`+ ChatType[chatType] + `",
"UserState": "`+ UserState[userState] + `",
"CallingState": "`+ CallingState[callingState] + `",
"Msg": "`+ Msg[msg] + `"
}`
return result;
}
- 这样一来,Unity 3D使用LitJson就能解析字符串的格式,用下面的方式将字符串变为objct就成为可能,可见,Unity LitJson插件在本质上是在寻找字符串的引号,来将Json字符串变为对象,但是它最坑人的一个点是,在字符串格式不符合它解析的时候不会报错,该作用域的代码也不会执行,对程序员并不友好:
JsonData jsonResult = JsonMapper.ToObject(Encoding.UTF8.GetString(data));
作者:艾孜尔江
转载请务必标明出处!