需求:获取传来的客户,关联的任意一辆汽车的名字。
正常情况下,我们收到的报文都是这个样子的:
{
"name": "小明",
"relCarList": [{
"carName": "路虎揽胜",
"carId": "1001"
}, {
"carName": "奥迪A8",
"carId": "1002"
}]
}
解析也很常规,这里使用的fastJson解析。
String org="{\n" +
"\t\"name\": \"小明\",\n" +
"\t\"relCarList\": [{\n" +
"\t\t\"carName\": \"路虎揽胜\",\n" +
"\t\t\"carId\": \"1001\"\n" +
"\t}, {\n" +
"\t\t\"carName\": \"奥迪A8\",\n" +
"\t\t\"carId\": \"1002\"\n" +
"\t}]\n" +
"}";
JSONObject jsonObject = JSONObject.parseObject(org);
JSONArray relCarList = jsonObject.getJSONArray("relCarList");
JSONObject jsonObjectInner = (JSONObject) relCarList.get(1);
String carName = jsonObjectInner.getString("carName");
System.out.println(carName);
但是,偏偏有些傻子传报文的时候,在外层包了双引号,如:
{
"name": "小明",
"relCarList": "[{\"carName\":\"路虎揽胜\",\"carId\":\"1001\"},{\"carName\":\"奥迪A8\",\"carId\":\"1002\"}]"
}
那就只能这么解析了:
String org="{\n" +
"\t\"name\": \"小明\",\n" +
"\t\"relCarList\": \"[{\\\"carName\\\":\\\"路虎揽胜\\\",\\\"carId\\\":\\\"1001\\\"},{\\\"carName\\\":\\\"奥迪A8\\\",\\\"carId\\\":\\\"1002\\\"}]\"\n" +
"}";
JSONObject jsonObject = JSONObject.parseObject(org);
String relCarList = jsonObject.getString("relCarList");
String substring = relCarList.substring(1, relCarList.length() - 1);
String replace = substring.replace("//", "");
JSONArray jsonArray = JSONObject.parseArray(relCarList);
JSONObject jsonObjectInner = (JSONObject) jsonArray.get(1);
String carName = jsonObjectInner.getString("carName");
System.out.println(carName);