JsonAttributeConverter.java 1.55 KB
package fi.codecrew.moya.model.converters;

import java.io.StringReader;
import java.sql.SQLException;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

import org.postgresql.util.PGobject;

@Converter(autoApply = true)
public class JsonAttributeConverter implements AttributeConverter<JsonObject, PGobject> {

    public PGobject convertToDatabaseColumn(JsonObject attribute) {
        if (attribute == null) {
            return null;
        }

        final PGobject dataValue = new PGobject();
        dataValue.setType("json");

        try {
            dataValue.setValue(attribute.toString());
        } catch (SQLException e) {
            // This will never run because PGobject.setValue() cannot really
            // throw an SQLException. There is nothing but setting a property.
            throw new RuntimeException("THIS SHOULD NEVER HAPPEN", e);
        }

        return dataValue;
    }

    public JsonObject convertToEntityAttribute(PGobject dbData) {

        // Has any?
        if (dbData == null) {
            return null;
        }

        // Correct type of object?
        if (dbData.getType().equals("json") == false) {
            throw new RuntimeException("Expected JSON object from database");
        }

        // Read as JSON object
        final StringReader stringReader = new StringReader(dbData.getValue());
        final JsonReader jsonReader = Json.createReader(stringReader);
        return jsonReader.readObject();
    }

}