JsonTypeHandler解析数据库json类型字段
背景:前端保存到数据库中的为json格式字符串。在解析后回显前端时需要使用到json格式。如果按照固定思维需要在后端增加很多的类字段以应对这个问题。解决的方案就是使用Map对象接收转换后的数据(这里的数据是json的格式存储的)
- 数据库类型
- 存储的json结构数据
-
配置json处理器类并使用注解方式配置
package com.ruoyi.common.mybatis;import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.toolkit.Assert; import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.MappedJdbcTypes; import org.apache.ibatis.type.MappedTypes; import com.ruoyi.common.utils.tduck.JsonUtils;import java.io.IOException;/*** Jackson 实现 JSON 字段类型处理器** @author hubin* @since 2019-08-25*/ @Slf4j @MappedTypes({Object.class}) @MappedJdbcTypes(JdbcType.VARCHAR) public class JacksonTypeHandler extends AbstractJsonTypeHandler<Object> {private static ObjectMapper objectMapper = new ObjectMapper();private Class<?> type;public JacksonTypeHandler(Class<?> type) {if (log.isTraceEnabled()) {log.trace("JacksonTypeHandler(" + type + ")");}Assert.notNull(type, "Type argument cannot be null");this.type = type;}public static void setObjectMapper(ObjectMapper objectMapper) {Assert.notNull(objectMapper, "ObjectMapper should not be null");JacksonTypeHandler.objectMapper = JsonUtils.getInstance();}@Overrideprotected Object parse(String json) {try {if (StrUtil.isBlank(json)) {return null;}return objectMapper.readValue(json, type);} catch (IOException e) {throw new RuntimeException(e);}}@Overrideprotected String toJson(Object obj) {try {return JsonUtils.objToJsonIgnoreNull(obj);} catch (JsonProcessingException e) {throw new RuntimeException(e);} catch (Exception e) {throw new RuntimeException(e);}} }
-
解析后的数据,在前端api响应中可以查看
-
总结。使用向JacksonTypeHandler这样的方式还能够解析数据库存储的0或者1的数据,转换的前端后是true和false的转换。