昨天在使用FastJson解析数组类型时报错autoType is not suppor
自己的demo代码如下
JSONArray jsonArray = new JSONArray();
JSONObject json = new JSONObject(true);
json.put("@type", "*******");
json.put("***", "***")
jsonArray.add(json);
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, jsonArray.toJSONString());
Request request = new Request.Builder()
.url(URL_AUDIT)
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
String resp = response.body().string();
System.out.println("返回参数:"+resp);
下面这个代码我可以做个说明,第三方需要我发送的"@type"字段必须放在第一个,不然无法解析,所以在FastJson初始化的时候传入一个true,就可以开启Json排序了。如果没有这个的话,Json默认是无序的。
JSONObject json = new JSONObject(true);
这里我是用的是okHttp ,因为对方返回的是JsonArray类型,获取返回参数为response.body().string()可以拿到那个JsonArray串,这里我的思路是用FastJson把这个JsonArray串解析为一个Json对象,因为业务的原因,这个JsonArray里只有一个Json,
错误代码如下:
JSONArray array = JSONArray.parseArray(resp);
JSONObject jsonObject = array.getJSONObject(0);
报错:autoType is not support
解决方法及思路如下:
因为FastJson中有自己的关键字定义 和我们业务中的"@type"关键字重复,‘@type’ 用于保留反序列化时类型信息,我们返回的 json 内容中恰好就含有这样的关键字,fastjson 当成了自己的预定义解析类型进行解析,故会报出刚才的错误。
这里我们使用Feature.DisableSpecialKeyDetec传入解析器中,禁用掉这个关键字解析就好。
正确代码如下:
JSONArray parse = (JSONArray) JSONArray.parse(resp, Feature.DisableSpecialKeyDetect);
JSONObject parseJson = parse.getJSONObject(0);
String type = parseJson.getString("@type");
System.out.println("@type:"+type);
String customization = parseJson.getString("customization");
System.out.println("customization:"+customization);
String retCode = parseJson.getString("retCode");
System.out.println("retCode="+retCode);
参考链接:https://www.dazhuanlan.com/dada1171/topics/1012827