mysql Sping Boot 将model的JSONArray字段返回为null

roejwanj  于 2023-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(106)

我在对象中有一个JSONArray字段:

@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数据库请求对象时(历史是JSON列并且有数据),Sping Boot 将其返回为null:

"history": {}
ua4mk5z4

ua4mk5z41#

最后,我解决了这个问题。

<dependency>
    <groupId>io.hypersistence</groupId>
    <artifactId>hypersistence-utils-hibernate-60</artifactId>
    <version>3.4.3</version>
</dependency>

首先,将上面的存储库添加到pom.xml。然后将代码更改为以下内容:

@Column(name = "_history", columnDefinition = "json")
@Type(JsonType.class)
private List<Map<String, Object>> history = new ArrayList<>();

一切都很顺利

相关问题