Spring Boot return list of objects as json

When using Spring Boot @RestController, we are able to return directly an Entity in json format, given that we are able to convert our Entity Class object to Json using Jackson, however if using a JSONObject in our entity like in the last post

//User.java @Entity @Data @Table[name = "users"] public class User { @Id private Long id; @NonNull private String username; @NonNull @Column[columnDefinition = "TEXT"] @Convert[converter= JSONObjectConverter.class] private JSONObject jsonData; }

Results in an error similar to the one below:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.json.JSONObject]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer

Using Jackson Annotations

So, given that Springboot uses Jackson by default to convert our Entity Object to JSON to return when using @RestController we can make use of Jackson Annotations: @JsonIgnore and @JsonProperty

So now lets annotate our JsonObject with @JsonIgnore to avoid serializing that specific attribute by default.

... @NonNull @Column[columnDefinition = "TEXT"] @Convert[converter= JSONObjectConverter.class] @JsonIgnore private JSONObject jsonData;

However, this results in our attribute named jsonData not being returned by our controller.

So how can we return an object that may be serialized to Json by Jackson.

Using @JsonProperty annotation so that we have a method to convert our attribute to a Jackson friendly object.

Below our jsonData attribute we will create the following method to Convert a JSONObject to a HashMap annotated with @JsonProperty:

//This is the name of our attribute @JsonProperty["jsonData"] public List getAsJsonString[] throws IOException, JSONException { return toMap[activity]; } //Reference for below code: //stackoverflow.com/questions/21720759/convert-a-json-string-to-a-hashmap public Map toMap[JSONObject object] throws JSONException { Map map = new HashMap[]; Iterator keysItr = object.keys[]; while[keysItr.hasNext[]] { String key = keysItr.next[]; Object value = object.get[key]; if[value instanceof JSONArray] { value = toList[[JSONArray] value]; } else if[value instanceof JSONObject] { value = toMap[[JSONObject] value]; } map.put[key, value]; } return map; } public List toList[JSONArray array] throws JSONException { List list = new ArrayList[]; for[int i = 0; i

Chủ Đề