下面是后台接收到的一个json串,里面包含了转义字符,后台使用fastjson来解析该串到javabean,结果报错,解析失败 。
{"bank_of_name":"1231231","account_type":"2","dealer_fullname":"111","dealer_briefname":"1111","contacts_number":"2121","obj_name":"123123","bank_of_no":"12312312","land_area":"121212","industry_type":"1212","obj_cardno":"1231231231","business_num":"11111111111","law_man_card":"12312312312","rate":"[\"{\\\"attach_capvalue2\\\":\\\"0\\\",\\\"capvalue\\\":\\\"22\\\",\\\"attach_capvalue1\\\":\\\"0\\\",\\\"attach_rate1\\\":\\\"0\\\",\\\"rate\\\":\\\"0.58\\\",\\\"channel_ab\\\":\\\"0406\\\",\\\"attach_rate2\\\":\\\"0\\\",\\\"card_type\\\":\\\"2\\\",\\\"sett_type\\\":\\\"0\\\"}\"]","contact":"11111","bank_name":"1231231","phone_num":"12312312","law_man":"1212","law_man_link":"123123123"},sysSign:110bc0fb8d19e56e0944d6a7f0d6ed2a
为什么会解析失败呢,我们先拿一个可以正常解析的字符串作为对比,
{"bank_of_name":"1231231","account_type":"2","dealer_fullname":"111","dealer_briefname":"1111","contacts_number":"2121","obj_name":"123123","bank_of_no":"12312312","land_area":"121212","industry_type":"1212","obj_cardno":"1231231231","business_num":"11111111111","law_man_card":"12312312312","rate":[{"attach_capvalue2":"0","capvalue":"22","attach_capvalue1":"0","attach_rate1":"0","rate":"0.58","channel_ab":"0406","attach_rate2":"0","card_type":"2","sett_type":"0"}],"contact":"11111","bank_name":"1231231","phone_num":"12312312","law_man":"1212","law_man_link":"123123123"}
通过对比发现,关键的地方在于rate字段的处理,前面的rate里面包含多层字符串,所以会出现多次转义,而后台使用POJO类里面是一个ArrayList类型,解析到的确实字符串,自然会报解析失败。
既然问题找到了,那接下来就是解决问题,因为使用的是第三方库,所以还是从前端上送json着手解决。
经过分析和排查,最后发现前端使用Map转Json过程中,多次使用的是字符串,看看下面两个方法,
public String mapToJSON(Map<String,String> map){
return JSON.toJSONString(map);
}
public String mapsToJSONArray(Map<String,String> ...map){
JSONArray jsonArray=new JSONArray();
for(int i=0;i<map.length;i++){
//jsonArray.add(mapToJSON(map[i]));
//这里是个坑,嵌套json时,如果采取上面的方式,将在{外面有引号
jsonArray.add(map[i]);
}
return jsonArray.toJSONString();
}
由于使用的是Map<String,String>类型来存储,导致json在转换jsonString时自动按照String类型来组了,需要修改Map的类型为Map<String,Object>,另外设计到List<Map<String,Object>>类型时,直接set即可,不要转换为String,再进行set操作。
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("dealer_fullname",dealer_fullname);
dataMap.put("dealer_briefname",dealer_briefname);
dataMap.put("contact",contact);
dataMap.put("contacts_number",contacts_number);
Map<String, String> rateMap = new HashMap<String, String>();
rateMap.put("rate",rate);
rateMap.put("capvalue",capvalue);
//String rateJson = mapsToJSONArray(rateMap);
ArrayList<Map<String, String>> rateList = new ArrayList<Map<String, String>>();
rateList.add(rateMap);
dataMap.put("rate", rateList);
String result = JSON.toJSONString(dataMap);
按上面方式即可得到标准的Json字符串。
网友评论