解析json异常, ObjectMapper注册的问题
- 背景。存储数据使用
json
格式,所以需要解析以获取json中的字段值。 - 所报异常
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
-
要解析的json
{"endDate": "2025-07-15", "startDate": "2025-07-14"}
-
解析具体实现
/*** 解析周期配置JSON*/
private CycleConfigDto parseCycleConfig(String cycleConfigJson) {if (cycleConfigJson == null || cycleConfigJson.trim().isEmpty()) {return new CycleConfigDto();}try {return objectMapper.readValue(cycleConfigJson, CycleConfigDto.class);} catch (Exception e) {log.error("解析周期配置JSON失败: {}", cycleConfigJson, e);return new CycleConfigDto();}
}
- 解析json所映射的对象
package com.help.projectcenter.domain.dto;import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.time.LocalDate;/*** 周期配置DTO** @author ruoyi* @date 2025-01-14*/
@Data
public class CycleConfigDto {/*** 月份(1-12,用于年周期)*/private Integer month;/*** 日期(1-31,用于年周期和月周期)*/private Integer day;/*** 星期几(1-7,1=周一,2=周二,...,7=周日,用于周周期)*/private Integer weekday;/*** 开始日期(用于指定日期周期)*/@JsonFormat(pattern = "yyyy-MM-dd")private LocalDate startDate;/*** 结束日期(用于指定日期周期)*/@JsonFormat(pattern = "yyyy-MM-dd")private LocalDate endDate;/*** 验证配置是否有效*/public boolean isValid() {// 基础验证:至少有一个配置项不为空return month != null || day != null || weekday != null || startDate != null || endDate != null;}/*** 验证年周期配置*/public boolean isValidYearConfig() {return month != null && month >= 1 && month <= 12&& day != null && day >= 1 && day <= 31;}/*** 验证月周期配置*/public boolean isValidMonthConfig() {return day != null && day >= 1 && day <= 31;}/*** 验证周周期配置*/public boolean isValidWeekConfig() {return weekday != null && weekday >= 1 && weekday <= 7;}/*** 验证指定日期配置*/public boolean isValidSpecificDateConfig() {return startDate != null && endDate != null && !endDate.isBefore(startDate);}
}