Work with json data
JSON in the HTML
The easiest way to use json on the page is to have a Java class automatically
serialized by Thymeleaf in a <script>
tag:
<script th:inline="javascript">
const myJson = /*[[${myObject}]]*/ ""; (1)
</script>
1 | The Thymeleaf code is inside comments so that the file can be validated as javascript by the editor, but this is optional. |
The instance named "myObject" will be recursively converted to json for any getter it has, provided that the attribute type can itself be converted.
To ignore an attribute use @JsonIgnore
To ignore empty or null attributes use @JsonInclude(JsonInclude.Include.NON_EMPTY)
To serialize an attribute that doesn’t have a getter, prefix it with @JsonProperty
Example:
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Product {
@JsonIgnore private User user;
@JsonProperty private String color = "red";
public User getUser() {
return user;
}
// No getter
// public String getColor() {
// return color;
//}
}
...
Product product = new ...
model.addAttribute("myObject", product);
The outcome of the previous example would be:
<script th:inline="javascript">
const myJson = { "color" : "red" }
</script>
Download json
When the frontend makes an ajax call and expects a json result, the above approach could be used by returning a view that embeds the java object automatically converted to json by Thymeleaf:
Creating a json response with <th:block th:inline="text">
A quicker approach is to
return the json directly using @ResponseBody
and MediaType.APPLICATION_JSON_VALUE
:
any resulting Map<String, Object>
would be converted to a json object where
map keys are the json attributes:
@RequestMapping(value ="/somedata", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody public Map<String, Object> getSomeData() {
Map<String, Object> data = new HashMap<>();
data.put("name1", "value1");
data.put("name2", "value2");
return result;
}
The value of the Map can itself be a Map in order to create nested objects.
- creating a json object with yadaUtil.makeJsonObject() - returning all the Model?
Upload json
Soon in this section:
-
uploading json data via javascript
-
uploading a json file as MultipartFile
-
parsing json with @RequestBody
-
parsing json with ObjectMapper()