前言:在開發(fā)的時候遇到一個問題袋马,一個xml格式的請求數(shù)據(jù)其中一個字段拼接的是json格式的數(shù)據(jù),json數(shù)據(jù)里面的雙引號導致xml格式錯誤秸应,導致服務(wù)端解析錯誤虑凛。
錯誤請求代碼
<Request T="101" T1="1" C="0" Version="8.1.20160817001" UserName="yzc" PassWord="1" Type="0" MobileType="HUAWEI VNS-AL00" Imei="862268034454116" AndroidVersion="6.0" SIMCardInfo="{"netWorkType":"0","phoneType":"1","dataState":"0","simState":"1","subScriberId":"null"}" SDCardSize="10.4GB" SDCardAvailSize="3.1GB" />
有經(jīng)驗的人看到這個請求應(yīng)該就會發(fā)現(xiàn)錯誤的地方
SIMCardInfo="{"netWorkType":"0","phoneType":"1","dataState":"0","simState":"1","subScriberId":"null"}"
字段內(nèi)部的雙引號會引起xml解析錯誤,正常情況下xml根據(jù)雙引號的位置只能解析SIMCardInfo="{"软啼,導致后面的數(shù)據(jù)沒有正確的雙引號標識解析錯誤
我們既要保證json內(nèi)部數(shù)據(jù)正確桑谍,還要保證整個xml請求數(shù)據(jù)正確,所以特殊情況就要特殊對待
解決方法
1祸挪、如果內(nèi)容中有單引號霉囚,就用雙引號括起來,如果內(nèi)容中有雙引號匕积,就用單引號括起來。
<example content1="內(nèi)容有單引號'用雙引號括起來" content2='內(nèi)容有雙引號"用單引號括起來' />
所以按照這種方法榜跌,上述請求可以轉(zhuǎn)換為這樣
<Request T="101" T1="1" C="0" Version="8.1.20160817001" UserName="yzc" PassWord="1" Type="0" MobileType="HUAWEI VNS-AL00" Imei="862268034454116" AndroidVersion="6.0" SIMCardInfo='{"netWorkType":"0","phoneType":"1","dataState":"0","simState":"1","subScriberId":"null"}' SDCardSize="10.4GB" SDCardAvailSize="3.1GB" />
2闪唆、使用轉(zhuǎn)義字符替換
<Request T="101" T1="1" C="0" Version="8.1.20160817001" UserName="yzc" PassWord="1" Type="0" MobileType="HUAWEI VNS-AL00" Imei="862268034454116" AndroidVersion="6.0" SIMCardInfo="{"netWorkType":"0","phoneType":"1","dataState":"0","simState":"1","subScriberId":"null","networkCountryIso":""}" SDCardSize="10.4GB" SDCardAvailSize="3.1GB"/>
我們在代碼編寫的時候,經(jīng)常需要拼接帶有雙引號字符串钓葫,我們也可以使用“\”轉(zhuǎn)義
"{\"simOperator\":\"" + simOperator + "\",\"netWorkType\":\"" + netWorkType + "\",\"phoneType\":\"" + phoneType + "\",\"dataState\":\"" + dataState + "\",\"simState\":\"" + simState+ "\",\"subScriberId\":\"" + subScriberId + "\",\"networkCountryIso\":\"" + networkCountryIso + "\"}"