Returning JSON as Response Spring Boot
Change your some model class like this
@Entity
@Table(name="some_table")
public class SomeModel {
@Id
@Column(name="p_col", nullable=false)
private Integer id;
@Column(name="s_col")
private String name
@Column(name="t_col")
private String json; // this column contains json data
@Column(name = "t_col", columnDefinition = "json")
@Convert(attributeName = "data", converter = JsonConverter.class)
private Map<String, Object> json = new HashMap<>();
//constructors
//getters and setters
}
Write a json converter class.
@Converter
public class JsonConverter
implements AttributeConverter<String, Map<String, Object>>
{
@Override
public Map<String, Object> convertToDatabaseColumn(String attribute)
{
if (attribute == null) {
return new HashMap<>();
}
try
{
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(attribute, HashMap.class);
}
catch (IOException e) {
}
return new HashMap<>();
}
@Override
public String convertToEntityAttribute(Map<String, Object> dbData)
{
try
{
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(dbData);
}
catch (JsonProcessingException e)
{
return null;
}
}
}
It will convert database json attribute to your desire results. Thanks
You need to define your json attribute as JsonNode so jackson can read it back and forrward, but mark is as @Transient
so JPA does not try to store it on database.
Then you can code getter/setter for JPA, where you translate from JsonNode to String back and forward. You define a getter getJsonString
that translate JsonNode json
to String
. That one can be mapped to a table column, like 'json_string', then you define a setter where you receive the String
from JPA and parse it to JsonNode that will be avaialable for jackson, jackson then will translate it to a json object not a string as you mention.
@Entity
@Table(name = "model")
public class SomeModel {
private Long id;
private String col1;
// Attribute for Jackson
@Transient
private JsonNode json;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
@Column(name ="col1")
public String getCol1() {
return col1;
}
// Getter and setter for name
@Transient
public JsonNode getJson() {
return json;
}
public void setJson(JsonNode json) {
this.json = json;
}
// Getter and Setter for JPA use
@Column(name ="jsonString")
public String getJsonString() {
return this.json.toString();
}
public void setJsonString(String jsonString) {
// parse from String to JsonNode object
ObjectMapper mapper = new ObjectMapper();
try {
this.json = mapper.readTree(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Notice, @Column
are defined at gettters because we need to indicate JPA to use getJsonString
and JPA requires consistency so all column's getters must be mark with @Columns
.