关于如何处理JSONObject.fromObject(Object obj)无法转换特殊日期(java.sql.Date,java.sql.Timestamp)格式的问题。

当使用JSONObject从对象转换时,遇到java.sql.Date和Timestamp类型转换失败的问题,可以自定义JSONValueProcessor接口实现转换。本文提供了解决方案,包括SQLDateProcessor、UtilDateProcessor和TimestampProcessor三个处理器,将日期转换为字符串格式。

关于JSONObject的封装,或者说使用,现在市面上很多。这里不做过多的描述,但是有种情况却不得不说明下,JSONObject进行对对象进行JSON格式转换,但是在转换过程中,遇到了

Java.sql.Date类型的属性无法完成转换,并且抛出异常:net.sf.json.JSONException: 

java.lang.reflect.InvocationTargetException


很多人遇到这个问题后,应该会查询百度等搜索引擎,那么可能得到一种类型转换的说法,我们也得到这样的说法,

后来多方测试,也确实是这个问题。如何解决?


或许很多人会说,那既然时间格式无法转换,我们可以转换设计类型嘛,数据库中我们不用date或datetime,直接用

varchar,而java中直接用String好了。确实这不失一个解决问题的办法,但是如果我们不改呢?


下面是我给出的设计图:



在这个设计图中,我给出了一个接口JsonValueProcessor ,这个接口可以自定义一些JSON类型转换器,正好,我就

分别定义了3种不同类型的类型转换器。


分析上图,我定义了3种角色:

1、类型转换器抽象接口:分别定义了2个接口方法,一个用于处理数组,一个用于处理属性类型;

2、类型转换器具体实现类:实现了上述抽象接口类的接口方法;

3、调用者:用户通过调用“调用者”的方法,完成由对象向JSONObject转换。


类型转换器抽象接口,由json-lib.jar提供,我们不必定义。


处理java.sql.Date类型属性的类型转换器:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lovo.util;  
  2.   
  3. import java.text.SimpleDateFormat;  
  4. import java.util.Date;  
  5.   
  6. import net.sf.json.JsonConfig;  
  7. import net.sf.json.processors.JsonValueProcessor;  
  8.   
  9. /** 
  10.  * 定义一个自己的时间适配处理器 
  11.  * @author Administrator 
  12.  * 
  13.  */  
  14. public class SQLDateProcessor implements JsonValueProcessor{  
  15.   
  16.     private String format = "yyyy-MM-dd hh:mm:ss";//自定义时间格式化的样式  
  17.     public SQLDateProcessor() {  
  18.         super();  
  19.         // TODO Auto-generated constructor stub  
  20.     }  
  21.       
  22.     public SQLDateProcessor(String format) {  
  23.         this.format = format;  
  24.     }  
  25.   
  26.     public Object processArrayValue(Object arg0, JsonConfig arg1) {  
  27.         // TODO Auto-generated method stub  
  28.         return arg0;  
  29.     }  
  30.     /** 
  31.      * 处理对象的值 
  32.      * str 这个参数是当前需要处理的属性名 
  33.      */  
  34.     public Object processObjectValue(String str, Object obj, JsonConfig arg2) {  
  35.         // TODO Auto-generated method stub  
  36.         String ret = "";  
  37.         if(obj instanceof java.sql.Date){  
  38.             SimpleDateFormat sdf = new SimpleDateFormat(format);  
  39.             ret = sdf.format(new Date(((java.sql.Date) obj).getTime()));  
  40.         }  
  41.         return ret;  
  42.     }  
  43.   
  44. }  



处理java.util.Date类型的类型转换器:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lovo.util;  
  2.   
  3. import java.text.SimpleDateFormat;  
  4. import java.util.Date;  
  5.   
  6. import net.sf.json.JsonConfig;  
  7. import net.sf.json.processors.JsonValueProcessor;  
  8.   
  9. /** 
  10.  * 定义一个自己的时间适配处理器 
  11.  * @author Administrator 
  12.  * 
  13.  */  
  14. public class UtilDateProcessor implements JsonValueProcessor{  
  15.   
  16.     private String format = "yyyy-MM-dd hh:mm:ss";//自定义时间格式化的样式  
  17.     public UtilDateProcessor() {  
  18.         super();  
  19.         // TODO Auto-generated constructor stub  
  20.     }  
  21.       
  22.     public UtilDateProcessor(String format) {  
  23.         this.format = format;  
  24.     }  
  25.   
  26.     public Object processArrayValue(Object arg0, JsonConfig arg1) {  
  27.         // TODO Auto-generated method stub  
  28.         return arg0;  
  29.     }  
  30.     /** 
  31.      * 处理对象的值 
  32.      * str 这个参数是当前需要处理的属性名 
  33.      */  
  34.     public Object processObjectValue(String str, Object obj, JsonConfig arg2) {  
  35.         // TODO Auto-generated method stub  
  36.         String ret = "";  
  37.         if(obj instanceof java.util.Date){  
  38.             SimpleDateFormat sdf = new SimpleDateFormat(format);  
  39.             ret = sdf.format(((Date) obj).getTime());  
  40.         }  
  41.         return ret;  
  42.     }  
  43.   
  44. }  



处理java.sql.Timestamp类型的类型转换器:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lovo.util;  
  2.   
  3. import java.text.SimpleDateFormat;  
  4. import java.util.Date;  
  5.   
  6. import net.sf.json.JsonConfig;  
  7. import net.sf.json.processors.JsonValueProcessor;  
  8.   
  9. /** 
  10.  * 定义一个自己的时间适配处理器 
  11.  * @author Administrator 
  12.  * 
  13.  */  
  14. public class TimestampProcessor implements JsonValueProcessor{  
  15.   
  16.     private String format = "yyyy-MM-dd hh:mm:ss";//自定义时间格式化的样式  
  17.     public TimestampProcessor() {  
  18.         super();  
  19.         // TODO Auto-generated constructor stub  
  20.     }  
  21.       
  22.     public TimestampProcessor(String format) {  
  23.         this.format = format;  
  24.     }  
  25.   
  26.     public Object processArrayValue(Object arg0, JsonConfig arg1) {  
  27.         // TODO Auto-generated method stub  
  28.         return arg0;  
  29.     }  
  30.       
  31.     /** 
  32.      * 处理对象的值 
  33.      *  str 这个参数是当前需要处理的属性名 
  34.      */  
  35.     public Object processObjectValue(String str, Object obj, JsonConfig arg2) {  
  36.         // TODO Auto-generated method stub  
  37.         String ret = "";  
  38.         if(obj instanceof java.sql.Timestamp){  
  39.             SimpleDateFormat sdf = new SimpleDateFormat(format);  
  40.             ret = sdf.format(((Date) obj).getTime());  
  41.         }  
  42.         return ret;  
  43.     }  
  44.   
  45. }  


调用者类:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lovo.util;  
  2.   
  3. import java.util.Iterator;  
  4. import java.util.Map;  
  5.   
  6. import net.sf.json.JSONObject;  
  7. import net.sf.json.JsonConfig;  
  8. import net.sf.json.processors.JsonValueProcessor;  
  9. /** 
  10.  * JSON格式转换类 
  11.  * @author Administrator 
  12.  * 
  13.  */  
  14. public class JSONUtil {  
  15.     /** 
  16.      * 将一个对象直接转换为一个JSONObject对象, 
  17.      * 同样适合于JSON格式的字符串 
  18.      * 但是如果存在java.sql.Date或者java.sql.Timestamp时间格式,调用例外一个toJson转换方法 
  19.      * @param obj 
  20.      * @return 
  21.      */  
  22.     public static JSONObject toJson(Object obj) {  
  23.         return JSONObject.fromObject(obj);  
  24.     }  
  25.       
  26.     /** 
  27.      *  
  28.      * @param obj 需要转换的参数 
  29.      * @param processors 类型转换器的集合,参数是一个Map集合,键代表需要转换类型的全路径,值是类型转换器 
  30.      * @return 
  31.      * @throws ClassNotFoundException 
  32.      */  
  33.     public static JSONObject toJson(Object obj,Map<String,JsonValueProcessor> processors) throws ClassNotFoundException{  
  34.         //定义一个JSONConfig对象,该对象可以制定一个转换规则  
  35.         JsonConfig config = new JsonConfig();  
  36.         if(processors != null && !processors.isEmpty()){  
  37.             Iterator<java.util.Map.Entry<String, JsonValueProcessor>> it = processors.entrySet().iterator();  
  38.             while (it.hasNext()) {  
  39.                 Map.Entry<java.lang.String, net.sf.json.processors.JsonValueProcessor> entry = (Map.Entry<java.lang.String, net.sf.json.processors.JsonValueProcessor>) it  
  40.                         .next();  
  41.                 String key = entry.getKey();  
  42.                 JsonValueProcessor processor = processors.get(key);  
  43.                 //反射获取到需要转换的类型  
  44.                 Class<?> cls = Class.forName(key);  
  45.                 config.registerJsonValueProcessor(cls, processor);  
  46.             }  
  47.         }  
  48.         return JSONObject.fromObject(obj, config);  
  49.     }  
  50. }  



客户端调用“调用者”类,来完成对象向JSONObject进行转换:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.test.util;  
  2.   
  3. import java.sql.Date;  
  4. import java.sql.Timestamp;  
  5. import java.util.HashMap;  
  6. import java.util.Map;  
  7.   
  8. import org.junit.Ignore;  
  9. import org.junit.Test;  
  10.   
  11. import com.lovo.util.SQLDateProcessor;  
  12. import com.lovo.util.JSONUtil;  
  13. import com.lovo.util.TimestampProcessor;  
  14. import com.lovo.util.User;  
  15.   
  16. import net.sf.json.JSONObject;  
  17. import net.sf.json.processors.JsonValueProcessor;  
  18.   
  19. public class JSONTest {  
  20.     @Test  
  21.     public void testJsonObjectOne() {  
  22.         String shortFormat = "yyyy-MM-dd";  
  23.         String longFormat = "yyyy-MM-dd hh:mm:ss";  
  24.   
  25.         Date sqlDate = new Date(System.currentTimeMillis());  
  26.         Timestamp createTime = new Timestamp(System.currentTimeMillis());  
  27.         User user = new User("高高", sqlDate, createTime);  
  28.           
  29.         // 定义一个类型转化器集合,键是需要转换的类型全路径,值是用于转换的类型转换器  
  30.         Map<String, JsonValueProcessor> processors = new HashMap<String, JsonValueProcessor>();  
  31.           
  32.         //有了2-3种时间转换器,那么我们设计时,就可以短时间格式用Date,长时间格式就是用Timestamp  
  33.         processors.put("java.sql.Date"new SQLDateProcessor(shortFormat));  
  34.           
  35. //      processors.put("java.util.Date", new UtilDateProcessor(shortFormat));  
  36.           
  37.         processors.put("java.sql.Timestamp"new TimestampProcessor(longFormat));  
  38.           
  39.         JSONObject json = null;  
  40.         try {  
  41.             json = JSONUtil.toJson(user, processors);  
  42.         } catch (ClassNotFoundException e) {  
  43.             // TODO Auto-generated catch block  
  44.             e.printStackTrace();  
  45.         }  
  46.   
  47.         System.out.println(json.toString());  
  48.     }  
  49.   
  50.     /** 
  51.      * 将一个JSON格式的字符串转换为JSONObject对象,并获得其值 
  52.      */  
  53.     @Ignore  
  54.     public void testJsonObjectTwo() {  
  55.         // {"createTime":"2016-06-03 04:05:23","birthday":"2016-06-03","name":"高高"}  
  56.         String str = "{'createTime':'2016-06-03 04:05:23','birthday':'2016-06-03','name':'1'}";  
  57.         JSONObject json = null;  
  58.         try {  
  59.             json = JSONUtil.toJson(str, null);  
  60.         } catch (ClassNotFoundException e) {  
  61.             // TODO Auto-generated catch block  
  62.             e.printStackTrace();  
  63.         }  
  64.   
  65.         System.out.println(json.get("name"));  
  66.         System.out.println(json.get("createTime"));  
  67.         System.out.println(json.get("birthday"));  
  68.     }  
  69.   
  70. }  



得到的结果是:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. {"createTime":"2016-06-03 05:09:49","birthday":"2016-06-03","name":"高高"}  


在JSONUtil类中,由于我们可以采用JSONConfig类来一次性注册多个类型转换器,所以我将多个类型转换器装配到

Map中,迭代Map集合采用反射机制来获取到需要转换的类型,向JSONConfig类中注册。


在这个过程中,封装了日期格式的传递,方便大家得到自己想要的日期格式。


任务描述 本关任务:使用SparkSQL完成数据分析。 相关知识 为了完成本关任务,你需要掌握:如何使用SparkSQL进行数据分析 FastJson 简述 JSON 协议使用方便,越来越流行,JSON 的处理器有很多,这里我介绍一下 FastJson,FastJson 是阿里的开源框架,被不少企业使用,是一个极其优秀的Json框架,Github地址:FastJson 。 FastJson 优点 FastJson 数度快,无论序列化和反序列化,都是当之无愧的fast 功能强大(支持普通JDK类包括任意Java Bean Class、Collection、Map、Date或enum) 零依赖(没有依赖其它任何类库) FastJson 简单使用 json字符串: String JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}"; JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR); String studentName = jsonObject.getString("studentName"); String studentAge = jsonObject.getString("studentAge"); System.out.println(studentName + ":" + studentAge); 实际输出: lily:12 json数组: String JSON_ARRAY_STR = "[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]"; //方法一 JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR); for (Object obj : jsonArray) { JSONObject jsonObject = (JSONObject) obj; System.out.println("studentName: " + jsonObject.getString("studentName") + ":" + " studentAge: " + jsonObject.getInteger("studentAge")); } //方法二 int size = jsonArray.size(); for (int i = 0; i < size; i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); System.out.println("studentName: " + jsonObject.getString("studentName") + ":" + " studentAge: " + jsonObject.getInteger("studentAge")); } 实际输出: studentName: lily: studentAge: 12 studentName: lucy: studentAge: 15 studentName: lily: studentAge: 12 studentName: lucy: studentAge: 15 编程要求 字段说明 字段 描述 TRIP_ID 每个行程的唯一标识符 CALL_TYPE 它标识用于请求此服务的方式。它可能包含三个可能值中的一个:A:使用滴滴打车、B:万顺叫车、C:曹操专车 ORIGIN_CALL 它包含每个电话号码的唯一标识符,用于至少要求一个服务。如果CALL_TYPE ='A',它会识别旅行的客户。否则,它假定为NULL值 ORIGIN_STAND 它包含出租车站的唯一标识符。如果CALL_TYPE ='B',它确定行程的起点。否则,它假定为NULL值 TAXI_ID 它包含执行每次旅行的出租车司机的唯一标识符 TIMESTAMP Unix时间戳(以秒为单位)。它确定了旅行的开始 POLYLINE 它包含一个映射为字符串的GPS坐标列表(即WGS84格式)。字符串的开头和结尾用括号标识(分别是[和])。每对坐标也用与[LONGITUDE,LATITUDE]相同的括号标识。该列表包含每15秒行程的一对坐标。最后一个列表项对应于旅程的目的地,而第一个列表项表示其开始 在右侧编辑器补充代码,完成以下需求: 将时间戳转换成时间,例如将 1560239495 转换成 2019-6-11 TRIP_ID CALL_TYPE
08-03
package com.msxf.pai.agent.workflow.application.listeners; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.ObjectUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; import com.baomidou.mybatisplus.core.toolkit.ObjectUtils; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.google.gson.*; import com.msxf.eyas.thread.MsxfRunnable; import com.msxf.pai.agent.agents.application.service.autoagent.AutoAgentChatItemDetailServiceImpl; import com.msxf.pai.agent.agents.application.service.autoagent.AutoAgentChatItemServiceImpl; import com.msxf.pai.agent.agents.application.service.autoagent.AutoAgentChatServiceImpl; import com.msxf.pai.agent.agents.domain.po.AutoAgentChat; import com.msxf.pai.agent.agents.domain.po.AutoAgentChatItem; import com.msxf.pai.agent.agents.domain.po.AutoAgentChatItemDetail; import com.msxf.pai.agent.common.entity.constant.MessageKeyConstants; import com.msxf.pai.agent.common.thread.ExecutorUtil; import com.msxf.pai.agent.common.utils.MessageUtils; import com.msxf.pai.agent.common.utils.SpringUtils; import com.msxf.pai.agent.common.utils.UuidUtil; import com.msxf.pai.agent.serving.application.util.SSEUtils; import com.msxf.pai.agent.serving.domain.enums.SseResponseEventEnum; import com.msxf.pai.agent.workflow.application.client.dto.autoagent.*; import com.msxf.pai.agent.workflow.domain.enums.AutoAgentChatTypeEnum; import com.msxf.pai.common.domain.dto.SessionUserInfo; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import okhttp3.Response; import okhttp3.sse.EventSource; import okhttp3.sse.EventSourceListener; import org.jetbrains.annotations.NotNull; import javax.annotation.Nullable; import java.util.*; import java.util.concurrent.*; @Slf4j public class AutoAgentChatSSEListener extends EventSourceListener { private final SessionUserInfo userInfo; private final AutoAgentData dto; private final Boolean chatType; private final String reqId; private final CountDownLatch latch; @Getter private Integer runStatus = 1; private final Map<String, List<AutoAgentRagVO>> ragMapLists = new ConcurrentHashMap<>(); private final List<AutoAgentRagVO> ragVOLists = new CopyOnWriteArrayList<>(); private final List<String> events = new CopyOnWriteArrayList<>(); private long eventStartTime = System.currentTimeMillis(); // 添加时间戳变量 private long totalTime; //总耗时 private final ScheduledExecutorService scheduler; private final String chatItemId = UuidUtil.getUUID(); //默认ai回答id public AutoAgentChatSSEListener(SessionUserInfo userInfo, AutoAgentData dto, CountDownLatch latch, ScheduledExecutorService scheduler) { this.reqId = dto.getAgentData().getRequestId(); this.chatType = dto.getAgentData().getDraftMode(); this.userInfo = userInfo; this.dto = dto; this.scheduler = scheduler; this.latch = latch; } @Override public void onOpen(@NotNull EventSource eventSource, @NotNull Response response) { super.onOpen(eventSource, response); log.info("connect to rag success:{}", response); } @Override public void onEvent(@NotNull EventSource eventSource, String id, String type, @NotNull String data) { log.info("auto agent chat rag send requestId:{}, id:{},type:{},data {}:", reqId, id, type, data); if (StringUtils.isNotBlank(data)) { events.add(data); AutoAgentRagVO agentRagVO = new AutoAgentRagVO(); long currentTime = System.currentTimeMillis(); // 计算间隔时间 long time = currentTime - eventStartTime; // 更新时间戳 eventStartTime = currentTime; totalTime = totalTime + time; agentRagVO.setTime(time); agentRagVO.setChatItemId(chatItemId); JsonObject jsonObject = JsonParser.parseString(data).getAsJsonObject(); JsonElement content = null; if (jsonObject.has(AutoAgentChatTypeEnum.CONTENT.getValue()) && !jsonObject.get(AutoAgentChatTypeEnum.CONTENT.getValue()).isJsonNull()) { content = jsonObject.get(AutoAgentChatTypeEnum.CONTENT.getValue()); } getResult(jsonObject, agentRagVO); if (ObjectUtils.isNotEmpty(agentRagVO.getError_message()) || ObjectUtils.isNotEmpty(agentRagVO.getError_code())) { runStatus = 0; if (dto.getStream()) { SSEUtils.pubMsg(reqId, AutoAgentChatTypeEnum.ERROR.getValue(), JSONObject.toJSONString(agentRagVO.getError_message())); } log.info("error_message : {}", JSONObject.toJSONString(agentRagVO.getError_message())); } else { CustomMetadata customMetadata = null; if (jsonObject.has(AutoAgentChatTypeEnum.CUSTOM_METADATA.getValue()) && !jsonObject.get(AutoAgentChatTypeEnum.CUSTOM_METADATA.getValue()).isJsonNull()) { JsonObject customMetadataJsonObject = jsonObject.get(AutoAgentChatTypeEnum.CUSTOM_METADATA.getValue()).getAsJsonObject(); // 使用Gson将JsonObject反序列化为customMetadata类实例 Gson gson = new Gson(); customMetadata = gson.fromJson(customMetadataJsonObject, CustomMetadata.class); } if (jsonObject.has(AutoAgentChatTypeEnum.TIMESTAMP.getValue()) && !jsonObject.get(AutoAgentChatTypeEnum.TIMESTAMP.getValue()).isJsonNull()) { long asLong = jsonObject.get(AutoAgentChatTypeEnum.TIMESTAMP.getValue()).getAsLong(); agentRagVO.setTimestamp(asLong); } agentRagVO.setCustom_metadata(customMetadata); writeRagVo(jsonObject, content, agentRagVO); agentRagVO.setId(ObjectUtils.isEmpty(customMetadata.getId()) ? UuidUtil.getUUID() : customMetadata.getId()); if (dto.getStream()) { List<RagFunctionResponse> functionResponse = agentRagVO.getFunction_response(); if (CollectionUtils.isNotEmpty(functionResponse)) { List<String> errorMessage = new ArrayList<>(); for (RagFunctionResponse ragFunctionResponse : functionResponse) { String error_message = ragFunctionResponse.getResponse().getError_message(); if (ObjectUtils.isNotEmpty(error_message)) { errorMessage.add(error_message); } } if (CollectionUtils.isNotEmpty(errorMessage)) { SSEUtils.pubMsg(reqId, AutoAgentChatTypeEnum.TOOL_ERROR.getValue(), JSONObject.toJSONString(agentRagVO)); } else { pushMessage(customMetadata, agentRagVO); } } else { pushMessage(customMetadata, agentRagVO); } } } ragVOLists.add(agentRagVO); ragMapLists.put(reqId, ragVOLists); } } private void pushMessage(CustomMetadata customMetadata, AutoAgentRagVO agentRagVO) { if (!ObjectUtils.isEmpty(customMetadata.getIs_runner_start()) && customMetadata.getIs_runner_start()) { SSEUtils.pubMsg(reqId, AutoAgentChatTypeEnum.START.getValue(), JSONObject.toJSONString(agentRagVO)); } else if (!ObjectUtils.isEmpty(customMetadata.getIs_runner_final()) && customMetadata.getIs_runner_final()) { SSEUtils.pubMsg(reqId, AutoAgentChatTypeEnum.END.getValue(), JSONObject.toJSONString(agentRagVO)); } else { SSEUtils.pubMsg(reqId, customMetadata.getType(), JSONObject.toJSONString(agentRagVO)); } } @Override public void onClosed(@NotNull EventSource eventSource) { scheduler.shutdown(); if (!dto.getStream()) { latch.countDown(); } else { SSEUtils.complete(reqId); } log.info("****** : sse close : *******"); List<AutoAgentRagVO> ragVO = getRagVO(reqId); if (!CollectionUtils.isEmpty(ragVO) && !chatType) { CompletableFuture.runAsync(new MsxfRunnable(() -> { try { asyncSaveChat(ragVO); } catch (Exception e) { log.error("save autoagent chat data fail ", e); } }), ExecutorUtil.antoAgentChatExecutor); } } @Override public void onFailure(@NotNull EventSource eventSource, @Nullable Throwable t, @Nullable Response response) { scheduler.shutdown(); String s = t != null ? t.getMessage() : response != null ? response.toString() : ""; runStatus = 0; String msg = MessageUtils.getMessage(MessageKeyConstants.MESSAGE_API_APP_SERVING_DSLSSELISTENER_QINGQIU_DUIHUA_JIEKOU_YICHANG_YICHANG_XINXI) + s; log.error("response : {}", response); JSONObject out = new JSONObject(); out.put("message", msg); if (!dto.getStream()) { AutoAgentRagVO agentRagVO = new AutoAgentRagVO(); agentRagVO.setError_message(msg); agentRagVO.setError_code("600"); ragVOLists.add(agentRagVO); ragMapLists.put(reqId, ragVOLists); latch.countDown(); throw new RuntimeException(out.toString()); } else { SSEUtils.pubMsg(reqId, SseResponseEventEnum.ERROR.getValue(), out.toString()); SSEUtils.complete(reqId); } ragVOLists.clear(); ragMapLists.clear(); } private void asyncSaveChat(List<AutoAgentRagVO> ragVO) { String chatId = dto.getAgentData().getChatId(); AutoAgentChatServiceImpl autoAgentChatService = (AutoAgentChatServiceImpl) SpringUtils.getBean("autoAgentChatServiceImpl"); AutoAgentChat autoAgentChat = autoAgentChatService.findByChatId(chatId); if (ObjectUtils.isEmpty(autoAgentChat)) { String value = dto.getAgentData().getQuestion(); if (value.length() > 30) { value = value.substring(0, 30) + "..."; } AutoAgentChat agentChat = AutoAgentChat.builder() .agentId(dto.getAgentId()) .chatId(chatId) .chatTitle(value) .chatSource(dto.getSource()) .createBy(String.valueOf(userInfo.getUserId())) .updateBy(String.valueOf(userInfo.getUserId())) .userId(String.valueOf(userInfo.getUserId())) .userName(userInfo.getUserName()) .createTime(new Date()) .updateTime(new Date()) .teamId(String.valueOf(userInfo.getOrgId())) .tenantId(userInfo.getTenantCode()) .teamName(userInfo.getOrgCode()) .runStatus(runStatus) .agentVersion(dto.getVersion()) .build(); // 保存对话表 autoAgentChatService.save(agentChat); } saveItem(dto, userInfo, ragVO, autoAgentChat); } private void saveItem(AutoAgentData dto, SessionUserInfo userInfo, List<AutoAgentRagVO> ragVO, AutoAgentChat autoAgentChat) { AutoAgentChatItemServiceImpl autoAgentChatItemService = (AutoAgentChatItemServiceImpl) SpringUtils.getBean("autoAgentChatItemServiceImpl"); AutoAgentChatItemDetailServiceImpl autoAgentChatItemDetailService = (AutoAgentChatItemDetailServiceImpl) SpringUtils.getBean("autoAgentChatItemDetailServiceImpl"); String chatId = dto.getAgentData().getChatId(); List<AutoAgentChatItem> items = new ArrayList<>(); List<AutoAgentChatItemDetail> itemDetails = com.google.common.collect.Lists.newArrayList(); String chatItemId = UuidUtil.getUUID(); String traceId = dto.getAgentData().getRequestId(); AutoAgentChatItem itemUser = AutoAgentChatItem.builder() .agentId(dto.getAgentId()) .chatId(chatId) .chatObj("Human") .chatItemId(chatItemId) .traceId(traceId) .chatValue(dto.getAgentData().getQuestion()) .createBy(String.valueOf(userInfo.getUserId())) .updateBy(String.valueOf(userInfo.getUserId())) .userId(String.valueOf(userInfo.getUserId())) .userName(userInfo.getUserName()) .createTime(new Date()) .updateTime(new Date()) .teamId(String.valueOf(userInfo.getOrgId())) .tenantId(userInfo.getTenantCode()) .teamName(userInfo.getOrgCode()) .globalVariables(dto.getVariables()) .runningTime(totalTime) .build(); if (CollectionUtils.isNotEmpty(dto.getFileList())) { itemUser.setChatFileInfo(JSON.parseArray(JSON.toJSONString(dto.getFileList()))); } items.add(itemUser); for (AutoAgentRagVO autoAgentRagVO : ragVO) { CustomMetadata customMetadata = autoAgentRagVO.getCustom_metadata(); if (!ObjectUtils.isEmpty(customMetadata) && !ObjectUtils.isEmpty(customMetadata.getIs_runner_final()) && customMetadata.getIs_runner_final()) { String itemId = autoAgentRagVO.getChatItemId(); AutoAgentChatItem itemAi = BeanUtil.copyProperties(itemUser, AutoAgentChatItem.class); itemAi.setChatObj("AI"); itemAi.setChatValue(autoAgentRagVO.getFinalResult()); itemAi.setChatItemId(itemId); items.add(itemAi); } } if (ragVO.size() == 1) { AutoAgentRagVO agentRagVO = ragVO.get(0); if (ObjectUtil.isNotEmpty(agentRagVO.getError_message())) { String itemId = agentRagVO.getChatItemId(); AutoAgentChatItem itemAi = BeanUtil.copyProperties(itemUser, AutoAgentChatItem.class); itemAi.setChatObj("FAIL"); itemAi.setChatValue(agentRagVO.getError_message()); itemAi.setChatItemId(itemId); items.add(itemAi); } } if (CollectionUtils.isNotEmpty(events)) { for (int i = 0; i < events.size(); i++) { AutoAgentChatItemDetail detail = createAutoAgentChatDetail(userInfo, traceId, chatItemId); detail.setDetailData(events.get(i)); detail.setExecuteTime(ObjectUtils.isEmpty(ragVO.get(i).getTime()) ? 0L : ragVO.get(i).getTime()); itemDetails.add(detail); } } autoAgentChatItemService.saveBatch(items); autoAgentChatItemDetailService.saveBatch(itemDetails); if (ObjectUtil.isNotEmpty(autoAgentChat)) { autoAgentChat.setUpdateTime(new Date()); autoAgentChat.setUpdateBy(String.valueOf(userInfo.getUserId())); } events.clear(); } @NotNull private static AutoAgentChatItemDetail createAutoAgentChatDetail(SessionUserInfo userInfo, String traceId, String chatItemId) { AutoAgentChatItemDetail detail = new AutoAgentChatItemDetail(); detail.setDetailId(IdUtil.fastSimpleUUID()); detail.setCreateBy(String.valueOf(userInfo.getUserId())); detail.setCreateTime(new Date()); detail.setUpdateTime(new Date()); detail.setUpdateBy(String.valueOf(userInfo.getUserId())); detail.setItemId(chatItemId); detail.setTraceId(traceId); return detail; } public List<AutoAgentRagVO> getRagVO(String reqId) { return CollectionUtils.isEmpty(ragMapLists.get(reqId)) ? Collections.emptyList() : ragMapLists.get(reqId); } private static void writeRagVo(JsonObject jsonObject, JsonElement content, AutoAgentRagVO agentRagVO) { if (jsonObject.has(AutoAgentChatTypeEnum.CONTENT.getValue()) && !content.isJsonNull()) { JsonArray parts = content.getAsJsonObject().get(AutoAgentChatTypeEnum.PARTS.getValue()).getAsJsonArray(); List<RagFunctionCall> functionCall = new CopyOnWriteArrayList<>(); List<RagFunctionResponse> functionResponse = new CopyOnWriteArrayList<>(); parts.forEach(o -> { JsonObject part = o.getAsJsonObject(); if (!part.get(AutoAgentChatTypeEnum.FUNCTION_CALL.getValue()).isJsonNull()) { JsonObject asJsonObject = part.get(AutoAgentChatTypeEnum.FUNCTION_CALL.getValue()).getAsJsonObject(); RagFunctionCall functionCall1 = getRagFunctionCall(asJsonObject); functionCall.add(functionCall1); } if (!part.get(AutoAgentChatTypeEnum.FUNCTION_RESPONSE.getValue()).isJsonNull()) { RagFunctionResponse ragFunctionResponse = getRagFunctionResponse(part); functionResponse.add(ragFunctionResponse); } if (!part.get(AutoAgentChatTypeEnum.TEXT.getValue()).isJsonNull() && (!part.get(AutoAgentChatTypeEnum.THOUGHT.getValue()).isJsonNull() && part.get(AutoAgentChatTypeEnum.THOUGHT.getValue()).getAsBoolean())) { agentRagVO.setThinkResult(part.get(AutoAgentChatTypeEnum.TEXT.getValue()).getAsString()); } if (!part.get(AutoAgentChatTypeEnum.TEXT.getValue()).isJsonNull() && part.get(AutoAgentChatTypeEnum.THOUGHT.getValue()).isJsonNull()) { agentRagVO.setFinalResult(part.get(AutoAgentChatTypeEnum.TEXT.getValue()).getAsString()); } }); Optional.of(functionCall).ifPresent(agentRagVO::setFunction_call); Optional.of(functionResponse).ifPresent(agentRagVO::setFunction_response); } } @NotNull private static RagFunctionCall getRagFunctionCall(JsonObject asJsonObject) { RagFunctionCall functionCall1 = new RagFunctionCall(); String id = asJsonObject.get("id").isJsonNull() ? null : asJsonObject.get("id").getAsString(); String name = asJsonObject.get("name").isJsonNull() ? null : asJsonObject.get("name").getAsString(); JsonObject args = asJsonObject.get("args").isJsonNull() ? null : asJsonObject.get("args").getAsJsonObject(); functionCall1.setArgs(args != null ? args.toString() : ""); functionCall1.setName(name); functionCall1.setId(id); return functionCall1; } @NotNull private static RagFunctionResponse getRagFunctionResponse(JsonObject part) { RagFunctionResponse ragFunctionResponse = new RagFunctionResponse(); RagResponse ragResponse = new RagResponse(); JsonObject asJsonObject = part.get(AutoAgentChatTypeEnum.FUNCTION_RESPONSE.getValue()).getAsJsonObject(); String id = asJsonObject.get("id").isJsonNull() ? null : asJsonObject.get("id").getAsString(); String name = asJsonObject.get("name").isJsonNull() ? null : asJsonObject.get("name").getAsString(); String scheduling = asJsonObject.get("scheduling").isJsonNull() ? null : asJsonObject.get("scheduling").getAsString(); String willContinue = asJsonObject.get("will_continue").isJsonNull() ? null : asJsonObject.get("will_continue").getAsString(); JsonObject response = asJsonObject.get(AutoAgentChatTypeEnum.RESPONSE.getValue()).isJsonNull() ? null : asJsonObject.get("response").getAsJsonObject(); String errorMessage = null; String result = null; String toolType = null; if (response != null) { errorMessage = response.get(AutoAgentChatTypeEnum.ERROR_MESSAGE.getValue()).isJsonNull() ? null : response.get("error_message").getAsString(); result = response.get("result").isJsonNull() ? null : response.get("result").getAsString(); toolType = response.get("tool_type").isJsonNull() ? null : response.get("tool_type").getAsString(); } ragFunctionResponse.setId(id); ragFunctionResponse.setName(name); ragFunctionResponse.setScheduling(scheduling); ragFunctionResponse.setWill_continue(willContinue); ragResponse.setError_message(errorMessage); ragResponse.setResult(result); ragResponse.setTool_type(toolType); ragFunctionResponse.setResponse(ragResponse); return ragFunctionResponse; } private static void getResult(JsonObject jsonObject, AutoAgentRagVO agentRagVO) { String errorCode = jsonObject.has(AutoAgentChatTypeEnum.ERROR_CODE.getValue()) && !jsonObject.get(AutoAgentChatTypeEnum.ERROR_CODE.getValue()).isJsonNull() ? jsonObject.get(AutoAgentChatTypeEnum.ERROR_CODE.getValue()).getAsString() : null; agentRagVO.setError_code(errorCode); String error_message = jsonObject.has(AutoAgentChatTypeEnum.ERROR_MESSAGE.getValue()) && !jsonObject.get(AutoAgentChatTypeEnum.ERROR_MESSAGE.getValue()).isJsonNull() ? jsonObject.get(AutoAgentChatTypeEnum.ERROR_MESSAGE.getValue()).getAsString() : null; agentRagVO.setError_message(error_message); } } 这个是我的业务代码,请帮我优化一下代码,减少重复代码并将解析工具统一为gson
最新发布
10-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值