最近,开发时遇到了这样一个问题:“服务器B无法正确解析由服务器A组装发送过来的JSON串”
前端传送到后端的字符串比较复杂,中间多次出现转义符“\”等信息,后台在拿到该字符串后,需添加一部分内容后组装成json串发送到另外的系统进行处理。
组装成的JSON串长这样:
{
"context":{ // deviceID、Response为前端传来的数据
"username": "test",
"tranType": "00",
"authType": ["00"],
"devices":{
"deviceID": "+XYZabcfefafaf\/efffahfsahfQ"
}
}
"Response":"[{\"asseration\":[{\"asseration\":\"effafhahfahfahfsa\",\"name\":\"Xiaoming\"}],\"pv\":{\"major\":1}}]"
}
复制代码
初级方式:利用字符串拼接
String username = "test";
String tranType = "00";
String authType = "[\"00\"]";
String deviceID = inVo.getDeviceID();
String Response = inVo.getResponse();
String request = "{\"Response\":\"" + Response +
"\", \"context\":{\"username\":\"" + username +
"\", \"tranType\":\"" + tranType +
"\", \"authType\":\"" + authType +
" , \"devices\"{\"devideID\":\"" + deviceID + "\"}}}"
复制代码
经过实际测试发现,当组装的JSON串比较简单(不包含deviceID、Response)时,服务器B是能够正确解析并处理JSON串的。
但是,当组装的json串中包含deviceID、Response时,最终组装成的request会将“\”识别为转义符,导致发送到后台的json中缺失部分信息,造成无法解析。
进阶方式:利用Map进行组装
String username = "test";
String tranType = "00";
String authType = "[\"00\"]";
String deviceID = inVo.getDeviceID();
String Response = inVo.getResponse();
Map<String, Object> request = new HashMap()<>;
Map<String, Object> contextInfo = new HashMap()<>;
Map<String, Object> deviceInfo = new HashMap()<>;
deviceInfo.put("devideID", deviceID);
contextInfo.put("username", username);
contextInfo.put("tranType", tranType);
contextInfo.put("authType", authType);
contextInfo.put("devices", deviceInfo);
request.put("context", contextInfo);
request.put("Response", Response);
复制代码
利用Map进行组装,无法正确处理 “authType”: [“00”],会把[“00”]作为一个整体(字符串”[“00”]”)进行处理,导致发送到后台的json中增加了部分信息,造成无法解析。
最终方式:利用JSONObject进行组装
String username = "test";
String tranType = "00";
JSONObject request = new JSONObject();
JSONObject contextInfo = new JSONObject();
JSONObject deviceInfo = new JSONObject();
deviceInfo.put("devideID", inVo.getDeviceID());
contextInfo.put("username", username);
contextInfo.put("tranType", tranType);
JSONArray authType = new JSONArray();
authType.put("00"); // "authType": ["00"],
contextInfo.put("authType", authType);
contextInfo.put("devices", deviceInfo);
request.put("context", contextInfo);
request.put("Response", inVo.getResponse());
复制代码
不多说,测试成功!
同时,JSONObject可以与String互相进行转换
request.toString()
JSONObject object = new JSONObject(request.toString());
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END