一个复杂JSON串引发的故障

博客讲述了在开发过程中遇到的服务器间JSON串解析错误的问题。主要涉及前端传送到后端的复杂字符串处理,包括使用字符串拼接、Map组装及JSONObject组装三种方式。初级方式在处理转义符时出现问题,进阶方式未能正确处理特定字段,最终通过使用JSONObject成功解决了JSON组装和解析的难题。
摘要由CSDN通过智能技术生成

最近,开发时遇到了这样一个问题:“服务器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}}]"
}
  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中缺失部分信息,造成无法解析。

  1. 进阶方式:利用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中增加了部分信息,造成无法解析。

  1. 最终方式:利用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());

不多说,测试成功!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值