In Kotlin, mapOf defines Map and it can build object structure with similar appearance of JSON. Also, you can build JSON elements one by one with MutableMap.
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fun list(taskList:List<Task>):Map<String,Any?>{
val taskMapList=mutableListOf<Map<String,Any?>>()
taskList.forEach{
val taskMap=mutableMapOf<String,Any?>()
taskMap["id"]=it.id
taskMap["name"]=it.name
taskMap["created_at"]=it.createdAt
taskMap["updated_at"]=it.updatedAt
taskMapList.add(taskMap)
}
val dataMap=mutableMapOf<String,Any?>()
dataMap["tasks"]=taskMapList
val jsonMap=mutableMapOf<String,Any?>()
jsonMap["data"]=dataMap
returnjsonMap
}
Now use TaskJsonView in TaskController. Add the following methods to TaskController.
Java
1
2
3
4
5
@ResponseBody
@GetMapping(produces=arrayOf("application/json"))
fun listJson():Map<String,Any?>{
returnTaskJsonView.list(taskRepository.findAll())
}
Launch the server and send JSON get request to http://localhost:8080/task, then the following response is returned. You must add "Accept=application/json" to the request header.
The data of success is built as {"data": { ... }}. This structure is basic and the same for all success JSON response. So export the frame into LayoutJsonView object.
1
2
3
4
5
6
7
src
-main
-kotlin
-com.example.myapp
-presentation
-layout
-LayoutJsonView
Java
1
2
3
4
5
6
7
packagecom.example.myapp.presentation.layout
objectLayoutJsonView{
fun success(data:Map<String,Any?>?):Map<String,Any?>{