JSONObject.parseObject解析数据后保持顺序不变

本文介绍了解决fastjson解析字符串数据后顺序改变的问题,提供了四种方法:解析时增加不调整顺序参数、配置有序对象、初始化json对象为有序对象及使用Gson解析,确保数据顺序一致。

在开发过程中遇到一个问题:服务器经过排序返回后的字符串数据在使用fastjson解析后,数据顺序发生了变化,这个问题也就是:使用fastjson解析数据后导致顺序改变或者说是如何保持String字符串转为json对象时顺序不变

解决方法:

方法一:解析时增加参数不调整顺序(亲测使用有效)

JSONObject respondeBodyJson = JSONObject.parseObject(str, Feature.OrderedField);

方法二:配置有序对象

JSONObject.parseObject(str,LinkedHashMap.class,Feature.OrderedField);

方法二:初始化json对象为有序对象

JSONObject retObj = new JSONObject(true);

方法三:使用Gson解析

JsonObject returnData = new JsonParser().parse(str).getAsJsonObject();

这样生成的json对象就与放入数据时保持一致了

注意:引入的fastjson相关的jar包版本要高于1.2.3,因为Feature.OrderedField是从1.2.3开始的

Map<String, String> pro = new HashMap<String, String>(); Put put; @Override protected void setup(Context context) throws IOException, InterruptedException { Connection connection = DBHelper.getConnection(); try { Statement statement = connection.createStatement(); String sql = "select * from province"; ResultSet resultSetA = statement.executeQuery(sql); while (resultSetA.next()) { String city_code = resultSetA.getString(1); String city_name = resultSetA.getString(2); pro.put(city_code, city_name); } } catch (SQLException e) { e.printStackTrace(); } } public void map(LongWritable key,Text value,Context context) throws IOException, InterruptedException { String line = value.toString(); //解析json数据 JSONObject jsonObject = JSONObject.parseObject(line); String[] data = new String[14]; data[0] = jsonObject.getString("id"); data[1] = jsonObject.getString("company_name"); data[2] = jsonObject.getString("eduLevel_name"); data[3] = jsonObject.getString("emplType"); data[4] = jsonObject.getString("jobName"); String salary=jsonObject.getString("salary"); if (salary.contains("K-")) { Double a =Double.valueOf(salary.substring(0,salary.indexOf("K"))); Double b =Double.valueOf(salary.substring(salary.indexOf("-")+1,salary.lastIndexOf("K"))); data[5] = (a+b)/2+""; }else { data[5]="0"; } data[6] = jsonObject.getString("createDate"); data[7] = jsonObject.getString("endDate"); String code = jsonObject.getString("city_code"); //data[8] = pro.get(code); data[8] = code; data[9] = jsonObject.getString("companySize"); data[10] = jsonObject.getString("welfare"); data[11] = jsonObject.getString("responsibility"); data[12] = jsonObject.getString("place"); data[13] = jsonObject.getString("workingExp"); //循环判空 for(String i : data) { if(i==null||i.equals("")) { return; } } String columnFamily = "info"; put= new Put(data[0].getBytes()); put.addColumn(columnFamily.getBytes(), "company_name".getBytes(), data[1].getBytes()); put.addColumn(columnFamily.getBytes(), "eduLevel_name".getBytes(), data[2].getBytes()); put.addColumn(columnFamily.getBytes(), "emplType".getBytes(), data[3].getBytes()); put.addColumn(columnFamily.getBytes(), "jobName".getBytes(), data[4].getBytes()); put.addColumn(columnFamily.getBytes(), "salary".getBytes(), data[5].getBytes()); put.addColumn(columnFamily.getBytes(), "createDate".getBytes(), data[6].getBytes()); put.addColumn(columnFamily.getBytes(), "endDate".getBytes(), data[7].getBytes()); put.addColumn(columnFamily.getBytes(), "city_name".getBytes(), data[8].getBytes()); put.addColumn(columnFamily.getBytes(), "companySize".getBytes(), data[9].getBytes()); put.addColumn(columnFamily.getBytes(), "welfare".getBytes(), data[10].getBytes()); put.addColumn(columnFamily.getBytes(), "responsibility".getBytes(), data[11].getBytes()); put.addColumn(columnFamily.getBytes(), "place".getBytes(), data[12].getBytes()); put.addColumn(columnFamily.getBytes(), "workingExp".getBytes(), data[13].getBytes()); context.write(NullWritable.get(), put); } 修改以上代码,但不改变输出
最新发布
11-26
@Override public ResponseDto getDepartmentTreeList(Integer departmentId,Integer isPeople) { Integer rootOrg; if (Objects.isNull(departmentId)) { rootOrg = ConfigUtil.getInt(ConfigUtil.ROOT_TISSUE); } else { rootOrg = departmentId; } String redisKey = ObjectUtil.join(Contacts.SYNTHESIZE_DEPART_TREE_CACHE,rootOrg,":",isPeople); if (RedisUtil.exists(redisKey)) { String dataStr = RedisUtil.get(redisKey); return ResponseDto.success(JSONArray.parseArray(dataStr)); } final DepartDto[] dto = new DepartDto[1]; List<DepartDto> departmentList = noticeMapper.getDepartmentList(null); Map<Integer, List<DepartDto>> collect = departmentList.stream().collect(Collectors.groupingBy(DepartDto::getParentid)); departmentList.forEach(e -> { if (Objects.equals(rootOrg, e.getId())) { dto[0] = e; } e.setChildNode(collect.get(e.getId())); }); List<DepartDto> collect1 = departmentList.stream().filter(e -> Objects.equals(rootOrg, e.getParentid())).collect(Collectors.toList()); if (isPeople == 1) { dto[0].setChildNode(collect1); RedisUtil.set(redisKey,JSONArray.toJSONString(dto),1,TimeUnit.DAYS); return ResponseDto.success(dto); } CountDownLatch countDownLatch = new CountDownLatch(collect1.size()); JSONArray childNodes = new JSONArray(); JSONObject deptDto = new JSONObject(); try { collect1.forEach(departDto-> executor.execute(()->{ JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(departDto)); if (Assert.isNotEmpty(departDto.getChildNode())) { JSONArray leader = getChildNodeLeaderList(departDto.getId()); JSONArray childNode = object.getJSONArray("childNode"); leader.addAll(childNode); object.put("childNode",leader); } childNodes.add(object); countDownLatch.countDown(); })); countDownLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } JSONArray leader = getChildNodeLeaderList(rootOrg); leader.addAll(childNodes); deptDto.putAll(JSONObject.parseObject(JSONObject.toJSONString(dto[0]))); deptDto.put("childNode",leader); JSONArray result = new JSONArray(); result.add(deptDto); RedisUtil.set(redisKey,JSONArray.toJSONString(result),1,TimeUnit.DAYS); return ResponseDto.success(result); }这个是刚才那段报错的代码 看一下
09-13
package com.gcvcloud.interfaceservice.service; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.gcvcloud.interfaceservice.domain.query.*; import com.gcvcloud.interfaceservice.mapper.HaiKangMapper; import com.hikvision.artemis.sdk.ArtemisHttpUtil; import com.hikvision.artemis.sdk.config.ArtemisConfig; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; @Service @Slf4j public class HaiKangService { @Autowired private HaiKangMapper haiKangMapper; @Autowired private WeComService weComService; @Value("${haikang.url}") private String url; @Value("${haikang.appKeyEvent}") private String appKey; @Value("${haikang.appSecretEvent}") private String appSecret; private static final String ARTEMIS_PATH = "/artemis"; @Transactional public void processWarnings(EventPayloads eventPayloads) throws Exception { EventParams params = eventPayloads.getParams(); // 使用LinkedHashMap保持插入顺序,并对相同eventId的事件进行合并处理 Map<String, MergedEventData> mergedEvents = new LinkedHashMap<>(); // 预处理事件数据,合并具有相同eventId的事件 for (EventData eventData : params.getEvents()) { String eventId = eventData.getEventId(); if (!mergedEvents.containsKey(eventId)) { mergedEvents.put(eventId, new MergedEventData(eventData)); } else { // 合并相同eventId的事件数据 mergedEvents.get(eventId).merge(eventData); } } // 按顺序处理合并后的事件 for (Map.Entry<String, MergedEventData> entry : mergedEvents.entrySet()) { EventPayload eventPayload = getEventPayload(eventPayloads, entry.getValue().getMergedEvent(), params); synchronized (eventPayload.getEventId().intern()) { processSingleEvent(eventPayload, entry.getValue().getMergedEvent()); } } } // 用于合并相同eventId的事件数据的辅助类 private static class MergedEventData { private EventData mergedEvent; public MergedEventData(EventData eventData) { this.mergedEvent = eventData; } public void merge(EventData eventData) { // 合并linkageResult数据 if (eventData.getLinkageResult() != null) { if (mergedEvent.getLinkageResult() == null) { mergedEvent.setLinkageResult(new ArrayList<>()); } mergedEvent.getLinkageResult().addAll(eventData.getLinkageResult()); } } public EventData getMergedEvent() { return mergedEvent; } } //事件处理 private void processSingleEvent(EventPayload eventPayload, EventData eventData) throws Exception { ArtemisConfig artemisConfig = new ArtemisConfig(url, appKey, appSecret); String searchDataApi = ARTEMIS_PATH + "/api/els/v1/events/search"; Map<String, String> path = new HashMap<String, String>(2) { { put("https://", searchDataApi); } }; SearchRequest searchRequest = new SearchRequest(); searchRequest.setHandleStatus(0); searchRequest.setStartTime(eventData.getHappenTime()); searchRequest.setEndTime(eventData.getStopTime()); searchRequest.setPageSize(20); searchRequest.setPageNo(1); String body = JSON.toJSONString(searchRequest); try { java.util.concurrent.TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.error("延时执行被中断: {}", e.getMessage()); } String artemis = ArtemisHttpUtil.doPostStringArtemis(artemisConfig, path, body, null, null, "application/json"); JSONObject responseJson = JSON.parseObject(artemis); JSONObject dataObj = responseJson.getJSONObject("data"); if (dataObj == null) { log.info("当前时间未查询到数据"); return; } JSONArray listArray = dataObj.getJSONArray("list"); if (listArray.isEmpty()) { log.info("当前时间未查询到数据"); return; } for (Object object : listArray) { JSONObject jsonObject = (JSONObject) object; // 处理resName等数据 JSONArray eventLogSrcList = jsonObject.getJSONArray("eventLogSrcList"); if (eventLogSrcList != null && !eventLogSrcList.isEmpty()) { JSONObject firstSrc = eventLogSrcList.getJSONObject(0); if (firstSrc != null) { String resName = firstSrc.getString("resName"); eventPayload.setLocationName(resName); } } Integer handleStatus = jsonObject.getInteger("handleStatus"); eventPayload.setHandleStatus(handleStatus); Integer eventLevel = jsonObject.getInteger("eventLevel"); eventPayload.setEventLevel(eventLevel); String remark = jsonObject.getString("remark"); eventPayload.setRemark(remark); String eventLevelValue = jsonObject.getString("eventLevelValue"); eventPayload.setAbility(eventLevelValue); List<EventPayload> existing = haiKangMapper.selectEventPayload(eventPayload.getEventId()); String timeEventpaylods = haiKangMapper.timeEventpaylods(eventPayload.getEventId()); String firstTime = haiKangMapper.firstTime(eventPayload.getEventId()); if (existing.isEmpty() || existing.get(0).getRemindCount()>=1 && existing.get(0).getRemindCount() < 3 ) { eventPayload.setRemindCount(1); eventPayload.setFirstRemindTime(getCurrentTimeString()); eventPayload.setLastRemindTime(getCurrentTimeString()); try { if (eventPayload.getPicUri() == null){ return; } haiKangMapper.insertEventPayload(eventPayload); log.info("插入成功"); weChatMediaUploader(eventPayload); // 只有新插入才发送提醒 } catch (Exception e) { // 检查是否是锁等待超时异常,如果是则重试 if (e.getMessage() != null && e.getMessage().contains("Lock wait timeout exceeded")) { log.warn("事件 {} 插入时发生锁等待超时,稍后重试", eventPayload.getEventId()); try { // 等待一段时间后重试 java.util.concurrent.TimeUnit.SECONDS.sleep(1); haiKangMapper.insertEventPayload(eventPayload); log.info("重试插入成功"); weChatMediaUploader(eventPayload); } catch (Exception retryException) { log.error("重试插入仍然失败: {}", retryException.getMessage()); } } else { // 可能是并发插入导致的唯一约束冲突,忽略或记录日志 log.info("事件 {} 插入时发生冲突,可能已被其他线程处理", eventPayload.getEventId()); } return; } } else if (calculateTimeDifference(firstTime) >= 900000 && existing.get(0).getRemindCount() >= 3 && existing.get(0).getRemindCount() < 6 ) { eventPayload.setRemindCount(4); eventPayload.setTwoRemindTime(getCurrentTimeString()); eventPayload.setLastRemindTime(getCurrentTimeString()); eventPayload.setHandleStatus(handleStatus); haiKangMapper.updateEventPayload(eventPayload); weChatMediaUploader(eventPayload); // 更新后发送提醒 log.info("更新成功"); } else if (calculateTimeDifference(timeEventpaylods) >= 900000 && existing.get(0).getRemindCount() >= 6 && existing.get(0).getRemindCount() < 9) { eventPayload.setRemindCount(7); eventPayload.setLastRemindTime(getCurrentTimeString()); eventPayload.setHandleStatus(handleStatus); haiKangMapper.updateEventPayload(eventPayload); weChatMediaUploader(eventPayload); // 更新后发送提醒 log.info("更新成功"); } } } //发送企业微信通知 private void sendReminder(EventPayload eventPayload) { String mobile = null; //如果是晚上7点到早上7点执行下方逻辑 if (isNightTime(eventPayload.getSendTime())){ if (eventPayload.getRemindCount()<3){ mobile = haiKangMapper.selectPhoneEventNight(); }else if (eventPayload.getRemindCount()<=6) { mobile = haiKangMapper.selectPhoneEventNightTwo(); }else if (eventPayload.getRemindCount()<=9) { return; } } if (eventPayload.getRemindCount()<=3){ mobile = haiKangMapper.selectPhoneEvent(); }else if (eventPayload.getRemindCount()<=6){ mobile = haiKangMapper.selectPhoneEventTwo(); }else if (eventPayload.getRemindCount()<=9){ mobile = haiKangMapper.selectPhoneEventThree(); } if (mobile == null) { log.warn("跳过发送预警通知:手机号为空,预警事件类别:{}", eventPayload.getAbility()); return; } String formattedSendTime = convertIsoToStandardFormat(eventPayload.getSendTime()); String content = String.format( "<font color=\"warning\">**预警事件提醒**</font> \n"+ "预警事件发生时间:<font color=\"warning\">%s</font>\n"+ ">预警事件级别:<font color=\"warning\">%s</font>\n" + ">预警事件名称:<font color=\"warning\">%s</font>\n" + ">预警时间地点:<font color=\"warning\">%s</font>\n", formattedSendTime, eventPayload.getAbility(), eventPayload.getSrcName(), eventPayload.getLocationName() ); String userId = weComService.getUserid(mobile); String imageUrl = eventPayload.getPicUri(); if (userId != null && !userId.trim().isEmpty()) { if (weComService.sendMarkdownMessage(userId, content)) { log.info("已发送预警事件给 {}", userId); } else { log.warn("未找到用户ID,跳过发送预警事件通知:手机号 {},事件类别:{}", mobile, eventPayload.getAbility()); } } if (eventPayload.getRemindCount() == 1 || eventPayload.getRemindCount() == 4 || eventPayload.getRemindCount() == 7) { if (imageUrl != null) { if (weComService.sendImageMessage(imageUrl, userId)) { log.info("已发送图片给 {}", userId); } } } } @Scheduled(fixedRate =1000) public void checkAndSendReminders() throws Exception { List<EventPayload> warnings = haiKangMapper.selectUnwarnedRecords(); SearchRequest searchRequest = new SearchRequest(); for (EventPayload warning : warnings) { ArtemisConfig artemisConfig = new ArtemisConfig(url, appKey, appSecret); String searchDataApi = ARTEMIS_PATH + "/api/els/v1/events/search"; Map<String, String> path = new HashMap<String, String>(2) { { put("https://", searchDataApi); } }; searchRequest.setStartTime(warning.getHappenTime()); searchRequest.setEndTime(warning.getStopTime()); searchRequest.setPageSize(20); searchRequest.setPageNo(1); String body = JSON.toJSONString(searchRequest); String artemis = ArtemisHttpUtil.doPostStringArtemis(artemisConfig, path, body, null, null, "application/json"); JSONObject responseJson = JSON.parseObject(artemis); JSONObject dataObj = responseJson.getJSONObject("data"); if (dataObj == null) { log.info("当前时间未查询到数据"); } else { JSONArray listArray = dataObj.getJSONArray("list"); if (listArray.isEmpty()) { log.info("当前时间未查询到数据"); } else { for (Object object : listArray) { JSONObject jsonObject = (JSONObject) object; if (jsonObject.getInteger("handleStatus") == 1) { haiKangMapper.updateEventStatus(warning.getEventId()); log.info("事件已处理,不再提醒!事件id为{}", warning.getEventId()); return; } } } } List<EventPayload> pendingEvents = haiKangMapper.selectPendingReminders(); for (EventPayload event : pendingEvents) { try { // 发送提醒 event.setRemindCount(event.getRemindCount() + 1); event.setLastRemindTime(getCurrentTimeString()); // 更新数据库 haiKangMapper.updateEventPayload(event); sendReminder(event); log.info("已发送第 {} 次提醒: {}", event.getRemindCount(), event.getEventId()); } catch (Exception e) { log.error("处理提醒失败: {}", e.getMessage(), e); } } String firstTime = haiKangMapper.firstTime(warning.getEventId()); String twoEventTime = haiKangMapper.twoTime(warning.getEventId()); if (calculateTimeDifference(firstTime) >= 900000 ) { List<EventPayload> pendingEventTwo = haiKangMapper.selectPendingRemindertwo(warning.getEventId()); for (EventPayload event : pendingEventTwo) { if (event.getRemindCount() == 3){ twoEventTime = getCurrentTimeString(); event.setRemindCount(event.getRemindCount() + 1); event.setLastRemindTime(getCurrentTimeString()); event.setTwoRemindTime(twoEventTime); // 更新数据库 haiKangMapper.updateEventPayload(event); weChatMediaUploader(event); }else{ try { // 发送提醒 event.setRemindCount(event.getRemindCount() + 1); event.setLastRemindTime(getCurrentTimeString()); event.setTwoRemindTime(twoEventTime); // 更新数据库 haiKangMapper.updateEventPayload(event); sendReminder(event); log.info("已发送第 {} 次提醒: {}", event.getRemindCount(), event.getEventId()); } catch (Exception e) { log.error("处理提醒失败: {}", e.getMessage(), e); } } } } if (!isNightTime(warning.getSendTime())) { String twoTime = haiKangMapper.twoTime(warning.getEventId()); if (calculateTimeDifference(twoTime) >= 900000) { List<EventPayload> pendingEventTwo = haiKangMapper.selectPendingRemindertree(warning.getEventId()); for (EventPayload event : pendingEventTwo) { // 发送提醒 if (event.getRemindCount() == 6){ event.setRemindCount(event.getRemindCount() + 1); event.setLastRemindTime(getCurrentTimeString()); // 更新数据库 haiKangMapper.updateEventPayload(event); weChatMediaUploader(event); }else { try { event.setRemindCount(event.getRemindCount() + 1); event.setLastRemindTime(getCurrentTimeString()); // 更新数据库 haiKangMapper.updateEventPayload(event); sendReminder(event); log.info("已发送第 {} 次提醒: {}", event.getRemindCount(), event.getEventId()); } catch (Exception e) { log.error("处理提醒失败: {}", e.getMessage(), e); } } } } } } } // 获取 EventPayload 对象 private static EventPayload getEventPayload(EventPayloads eventPayloads, EventData eventPayloades, EventParams params) { EventPayload eventPayload = new EventPayload(); eventPayload.setAbility(params.getAbility()); eventPayload.setSrcIndex(eventPayloades.getSrcIndex()); eventPayload.setSrcType(eventPayloades.getSrcType()); eventPayload.setHappenTime(eventPayloades.getHappenTime()); eventPayload.setEventId(eventPayloades.getEventId()); eventPayload.setSrcName(eventPayloades.getSrcName()); eventPayload.setEventType(eventPayloades.getEventType()); eventPayload.setMethod(eventPayloads.getMethod()); eventPayload.setSendTime(params.getSendTime()); eventPayload.setStopTime(eventPayloades.getStopTime()); List<LinkageResult> linkageResult = eventPayloades.getLinkageResult(); // 解析 content 字段提取 picUrls 和 svrIndexCode if (linkageResult != null && !linkageResult.isEmpty()) { for (LinkageResult result : linkageResult) { String content = result.getContent(); if (content != null && !content.isEmpty()) { try { // 解析 JSON 数组字符串 JSONArray contentArray = JSON.parseArray(content); if (contentArray != null && !contentArray.isEmpty()) { // 获取第一个元素(根据您的数据示例) JSONObject contentObj = contentArray.getJSONObject(0); if (contentObj != null) { // 提取 svrIndexCode String svrIndexCode = contentObj.getString("svrIndexCode"); eventPayload.setSvrIndexCode(svrIndexCode); // 提取 picUrls JSONArray picUrlsArray = contentObj.getJSONArray("picUrls"); if (picUrlsArray != null && !picUrlsArray.isEmpty()) { // 获取第一个图片 URL String picUrl = picUrlsArray.getString(0); eventPayload.setPicUri(picUrl); } } } } catch (Exception e) { log.error("解析 content 字段失败: {}", e.getMessage(), e); } } } } return eventPayload; } // 计算时间差 public static long calculateTimeDifference(String timeString1) { if (timeString1 == null){ return 0; } try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Date date1 = sdf.parse(timeString1); String formattedDate = sdf.format(new Date()); Date date2 = sdf.parse(formattedDate); return date2.getTime() - date1.getTime(); } catch (Exception e) { log.error("时间计算错误: {}", e.getMessage()); return 0; } } //获取当前时间字符串 public static String getCurrentTimeString() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); return sdf.format(new Date()); } //图片上传 public void weChatMediaUploader(EventPayload eventPayload) throws Exception { PictureRequest pictureRequest = new PictureRequest(); String imageUrl = eventPayload.getPicUri(); if (imageUrl == null){ return; } ArtemisConfig artemisConfig = new ArtemisConfig(url, appKey, appSecret); String pictureDataApi = ARTEMIS_PATH +"/api/video/v1/events/picture"; Map<String,String> path = new HashMap<String,String>(2){ { put("https://",pictureDataApi); } }; pictureRequest.setSvrIndexCode(eventPayload.getSvrIndexCode()); pictureRequest.setPicUri(imageUrl); pictureRequest.setNetProtocol("http"); String body=JSON.toJSONString(pictureRequest); String result =ArtemisHttpUtil.doPostStringArtemis(artemisConfig,path,body,null,null,"application/json"); JSONObject responseJson = JSON.parseObject(result); JSONObject dataObj = responseJson.getJSONObject("data"); if (dataObj!=null){ imageUrl = dataObj.getString("picUrl"); eventPayload.setPicUri(imageUrl); }else { return; } sendReminder(eventPayload); } /** * 根据事件发生时间判断是否为夜间时段 * @param eventTime 事件发生时间,格式为 "yyyy-MM-dd HH:mm:ss.SSS" * @return true表示夜间(19:00-7:00),false表示白天(7:00-19:00) */ private boolean isNightTime(String eventTime) { try { if (eventTime == null || eventTime.isEmpty()) { return false; } LocalDateTime dateTime; // 处理ISO 8601格式 if (eventTime.contains("T")) { // 标准化ISO格式时间字符串 String normalizedTime = eventTime; // 移除时区信息 if (normalizedTime.contains("+")) { normalizedTime = normalizedTime.substring(0, normalizedTime.indexOf("+")); } else if (normalizedTime.endsWith("Z")) { normalizedTime = normalizedTime.substring(0, normalizedTime.length() - 1); } DateTimeFormatter isoFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSS]"); dateTime = LocalDateTime.parse(normalizedTime, isoFormatter); } else { // 处理标准格式 DateTimeFormatter formatter = eventTime.contains(".") ? DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS") : DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); dateTime = LocalDateTime.parse(eventTime, formatter); } int hour = dateTime.getHour(); return hour >= 19 || hour < 7; } catch (Exception e) { log.error("解析事件时间失败,时间字符串: {}, 错误: {}", eventTime, e.getMessage()); return false; } } /** * 将ISO 8601格式的时间转换为标准格式 * @param isoTime ISO 8601格式的时间字符串 * @return 标准格式的时间字符串 */ private String convertIsoToStandardFormat(String isoTime) { if (isoTime == null || isoTime.isEmpty()) { return getCurrentTimeString(); // 返回当前时间作为默认值 } try { LocalDateTime dateTime; // 处理ISO 8601格式 if (isoTime.contains("T")) { // 标准化ISO格式时间字符串 String normalizedTime = isoTime; // 移除时区信息 if (normalizedTime.contains("+")) { normalizedTime = normalizedTime.substring(0, normalizedTime.indexOf("+")); } else if (normalizedTime.endsWith("Z")) { normalizedTime = normalizedTime.substring(0, normalizedTime.length() - 1); } DateTimeFormatter isoFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSS]"); dateTime = LocalDateTime.parse(normalizedTime, isoFormatter); } else { // 如果已经是标准格式,直接解析 DateTimeFormatter formatter = isoTime.contains(".") ? DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS") : DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); dateTime = LocalDateTime.parse(isoTime, formatter); } // 转换为 yyyy-MM-dd HH:mm:ss 格式 return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); } catch (Exception e) { log.error("时间格式转换失败,使用原始时间: {}, 错误: {}", isoTime, e.getMessage()); return isoTime; // 转换失败时返回原始时间 } } } 帮我改改
10-31
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值