HTMLで表示するViewは作りましたから、次は API を作ります。 一覧が取得できる簡単な API を考えます。
Return value of the controller method can be Kotlin Map, which will be converted well to JSON. To be flexible, to make JSON structure changeable, create TaskJsonView object and add method to return the Map, not data class.
Create View to Return JSON
Java
1
2
3
4
5
6
7
src
-main
-kotlin
-com.example.myapp
-presentation
-task
-TaskJsonView.kt
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
packagecom.example.myapp.presentation.task
importcom.example.myapp.domain.task.Task
objectTaskJsonView{
fun list(taskList:List<Task>):Map<String,Any?>{
returnmapOf(
"data"tomapOf(
"tasks"totaskList.map{
mapOf(
"id"toit.id,
"name"toit.name,
"created_at"toit.createdAt?.toString(),
"updated_at"toit.updatedAt?.toString()
)
}
)
)
}
}
In Kotlin, we can define map with mapOf function, so we can build the map corresponding to the JSON in looking JSON like structure. Of course, we can use MutableMap and add items one by one.
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
}
Use TaskJsonView in TaskController. Add the following method 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 GET request to http://localhost:8080/task for the JSON, then the following data will be returned. You must add "Accept=application/json" to request header.
Here, the application returns actual data with the format {"data": { ... }}. This structure is the same in the whole application, then let’s extract the structural part to LayoutJsonView.
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?>{