Spring Boot从MySQL查询后实体类JSONArray字段返回null问题
问题:MySQL JSON列查询后返回空对象而非实际数据
问题重现代码
实体类字段定义
@Column(name = "_history", columnDefinition = "JSON") @Convert(converter = JSONArrayConverter.class) private JSONArray history;
JSONArrayConverter实现
@JsonSerialize @Converter(autoApply = true) public class JSONArrayConverter implements AttributeConverter<JSONArray, String> { public static final Logger LOGGER = LoggerFactory.getLogger(JSONObjectConverter.class); @Override public String convertToDatabaseColumn(JSONArray array) { LOGGER.debug(array.toString()); if (array == null) return new JSONArray().toString(); String data = null; try { data = array.toString(); } catch (final Exception e) { LOGGER.error("JSON writing error", e); } return data; } @Override public JSONArray convertToEntityAttribute(String data) { if (_EMPTY.equals(data) || data == null || "[]".equals(data)) return new JSONArray(); JSONArray array = null; try { array = new JSONArray(data); } catch (final Exception e) { LOGGER.error("JSON reading error", e); } return array; } }
现象
从MySQL查询实体时,history字段(JSON列且存有数据)返回空对象:
"history": {}
排查与修复步骤
- 解决Jackson序列化适配问题
默认Jackson无法正确序列化org.json.JSONArray类型,导致输出空对象。需要自定义序列化器:
public class JSONArraySerializer extends JsonSerializer<JSONArray> { @Override public void serialize(JSONArray jsonArray, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeRawValue(jsonArray.toString()); } }
- 修正注解位置
移除转换器类上的@JsonSerialize,将其移到实体字段上并指定自定义序列化器:
@Column(name = "_history", columnDefinition = "JSON") @Convert(converter = JSONArrayConverter.class) @JsonSerialize(using = JSONArraySerializer.class) private JSONArray history;
- 补全未定义常量
转换器中_EMPTY常量未定义,需补充:
private static final String _EMPTY = "";
- 修正日志类引用
日志对象错误引用JSONObjectConverter.class,改为当前转换器类:
public static final Logger LOGGER = LoggerFactory.getLogger(JSONArrayConverter.class);
验证
修改完成后重新查询,history字段将正确返回数据库中存储的JSON数组数据。
内容的提问来源于stack exchange,提问作者Hajitsu
相关产品推荐
相关产品推荐

