0

I have a JSONArray field in the object:

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

and this is 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 when requesting the object from MySQL database(history is JSON column and has data), Spring boot returns it as null:

"history": {}
3
  • did you verify if the converter logic gets invoked? is the mapping working? Commented Jun 12, 2023 at 16:54
  • String data = null; <-- seems like that is firing a little too often maybe? Commented Jun 12, 2023 at 17:06
  • @easleyfixed it's ok. I changed to stackoverflow.com/a/67849195/1240052 but not work Commented Jun 12, 2023 at 17:39

1 Answer 1

0

Finally, I solved this issue.

<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 changed the codes to below:

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

and everything works for me.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.