Json数据:
[{“flow”: 215462, “timeNode”: “2023-05-26 13:55:00”}]
表数据对象文件
@TableName(value="table_name", autoResultMap = true)
........
public class EquipmentFlowDO extends BaseDO {
/**
* id
*/
@TableId
private Long id;
/**
* 流量数据
*/
@TableField(typeHandler = EquipmentFlowTypeHandler.class)
private List<EquipmentFlowVO> data;
json映射的类
@Data
public class EquipmentFlowVO {
@Schema(description = "时间节点")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime timeNode;
@Schema(description = "流量值")
private Integer flow;
}
json类型转化
/**
* @author fsg
* @apiNote 类型转换器:所有点位数据
* @date 2023年5月22日
* @see com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler
*/
@MappedTypes({Object.class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class EquipmentFlowTypeHandler extends AbstractJsonTypeHandler<List<EquipmentFlowVO>> {
private static final Logger log = LoggerFactory.getLogger(EquipmentFlowTypeHandler.class);
private static final ObjectMapper mapper = new ObjectMapper();
static {
// 转换为格式化的json
mapper.enable(SerializationFeature.INDENT_OUTPUT);
// 如果json中有新增的字段并且是实体类类中不存在的,不报错
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 下面配置解决LocalDateTime序列化的问题
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
JavaTimeModule javaTimeModule = new JavaTimeModule();
//日期序列化
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//日期反序列化
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
mapper.registerModule(javaTimeModule);
}
public EquipmentFlowTypeHandler(Class<?> type) {
if (log.isTraceEnabled()) {
log.trace("EquipmentFlowTypeHandler(" + type + ")");
}
Assert.notNull(type, "Type argument cannot be null");
}
@Override
protected List<EquipmentFlowVO> parse(String json) {
if (StrUtil.isEmpty(json)) {
return new ArrayList<>();
}
try {
return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, EquipmentFlowVO.class));
} catch (IOException e) {
log.error("json parse err,json:{}", json, e);
throw new RuntimeException(e);
}
}
@Override
protected String toJson(List<EquipmentFlowVO> list) {
try {
// 格式化时间
return mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
.registerModules(new JavaTimeModule())
.writeValueAsString(list);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}