今天在測試時,錯誤停留在了以下的代碼行
Object object = new ObjectMapper().readValue(JSON.toJSONString(procInst.getForm()), Object.class);
報錯信息:com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "$ref"
查看錯誤日志,發現是阿里巴巴的Fastjson在轉換數據出現的錯誤,錯誤中提到了$ref,了解了一下是因為在傳輸的數據中出現相同的對象時,fastjson
默認開啟引用檢測將相同的對象寫成引用的形式 默認開啟引用檢測將相同的對象寫成引用的形式。
舉個例子:
JSONObject obj = new JSONObject();
obj.put("obj", "111");JSONObject a = new JSONObject();
a.put("id", "a");
a.put("obj", obj);JSONObject b = new JSONObject();
b.put("id", "b");
b.put("obj", obj);JSONObject c = new JSONObject();
c.put("a", a);
c.put("b", b);System.out.println(c);
//{"a":{"id":"a","obj":{"obj":"111"}},"b":{"id":"b","obj":{"$ref":"$.a.obj"}}}System.out.println(JSON.toJSONString(c, SerializerFeature.DisableCircularReferenceDetect));
//{"a":{"id":"a","obj":{"obj":"111"}},"b":{"id":"b","obj":{"obj":"111"}}}
JSON.toJSONString使用的是com.alibaba.fastjson.JSON(錯誤發生在這里)
ObjectMapper使用的是jackson
親測幾種解決方式:
一、改為強轉:Object object = (Object)procInst.getForm();
二、使用jackson來解析為字符:new ObjectMapper().writeBalueAsString(procInst.getForm());
三、局部關閉,使用
SerializerFeature.DisableCircularReferenceDetect
關閉循環引用:Object object = new ObjectMapper().readValue(JSON.toJSONString(procInst.getForm(), SerializerFeature.DisableCircularReferenceDetect), Object.class);
四、全局關閉,在
SpringBoot
項目的json
配置中將循環引用關閉。FastJson
的配置增加:fastConverter.setFeatures(SerializerFeature.DisableCircularReferenceDetect);
五、在字段的注解上,指定序列化關閉循環引用:
@JSONField(serialzeFeatures = {SerializerFeature.DisableCircularReferenceDetect})
private List<Object> objectList;
六、禁止序列化(但實際是要用的,沒辦法,不用的話可以禁用)
@JSONField(serialize = false)
private List<Order> orderList;