fix: 修复 parseWorkflowResponse 解析 Coze 工作流双编码 JSON 数据
Coze 工作流返回的 output 字段是双编码的 JSON 字符串:
{"output": ""{\\\"calories\\\":...}\""}
修复方案:
1. 第一次解析:JSON.parseObject() 去掉外层引号,得到字符串
2. 第二次解析:JSON.parseObject() 解析该字符串,得到最终的营养数据对象
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -703,19 +703,49 @@ public class ToolCommunityServiceImpl implements ToolCommunityService {
|
|||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private Map<String, Object> parseWorkflowResponse(Object data) {
|
private Map<String, Object> parseWorkflowResponse(Object data) {
|
||||||
if (data == null) return null;
|
if (data == null) return null;
|
||||||
|
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
Map<String, Object> dataMap = null;
|
||||||
|
|
||||||
if (data instanceof Map) {
|
if (data instanceof Map) {
|
||||||
return (Map<String, Object>) data;
|
dataMap = (Map<String, Object>) data;
|
||||||
}
|
} else if (data instanceof String) {
|
||||||
// 如果是 JSON 字符串,尝试解析
|
|
||||||
if (data instanceof String) {
|
|
||||||
try {
|
try {
|
||||||
return JSON.parseObject((String) data, Map.class);
|
dataMap = JSON.parseObject((String) data, Map.class);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("Failed to parse workflow response as JSON: {}", e.getMessage());
|
log.warn("Failed to parse workflow response as JSON: {}", e.getMessage());
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return null;
|
|
||||||
|
if (dataMap == null) return null;
|
||||||
|
|
||||||
|
// 处理 Coze 工作流返回的 output 字段(可能是双编码的 JSON 字符串)
|
||||||
|
Object outputField = dataMap.get("output");
|
||||||
|
if (outputField != null) {
|
||||||
|
try {
|
||||||
|
// 第一次解析:从字符串去掉外层引号(因为 output 本身是 JSON 字符串)
|
||||||
|
String outputStr = outputField instanceof String
|
||||||
|
? (String) outputField
|
||||||
|
: outputField.toString();
|
||||||
|
|
||||||
|
// 第二次解析:解析内部的 JSON 对象
|
||||||
|
Map<String, Object> output = JSON.parseObject(outputStr, Map.class);
|
||||||
|
result.put("output", output);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("Failed to parse workflow output field: {}", e.getMessage());
|
||||||
|
result.put("output", outputField);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 保留其他字段
|
||||||
|
dataMap.forEach((key, value) -> {
|
||||||
|
if (!"output".equals(key)) {
|
||||||
|
result.put(key, value);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Reference in New Issue
Block a user