The JSONArray field of the Spring Boot returned model is empty
P粉076987386
P粉076987386 2023-09-12 15:56:44
0
1
634

I have a JSONArray field in the object:

@Column(name = "_history", columnDefinition = "JSON")
@Convert(converter = JSONArrayConverter.class)
private JSONArray history;

This is the code for 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;
    }
}

The problem is that when requesting the object from the MySQL database (history is a JSON column and has data), Spring Boot returns it as empty:

"history": {}
P粉076987386
P粉076987386

reply all(1)
P粉496886646

Finally, I solved the problem.

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

First, add the above repository to pom.xml. Then change the code to the following:

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

Then everything works fine.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template