Here is continuation from Kotlin 1.2.0 + Spring: create Web Application (2 of 4).
Create View for Json
1 2 3 4 5 6 7 |
src - main - kotlin - com.example.myapp - presentation - task - TaskJsonView.kt |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.example.myapp.presentation.task import com.example.myapp.domain.task.Task object TaskJsonView { fun list(taskList: List<Task>): Map<String, Any?> { return mapOf( "data" to mapOf( "tasks" to taskList.map { mapOf( "id" to it.id, "name" to it.name, "created_at" to it.createdAt?.toString(), "updated_at" to it.updatedAt?.toString() ) } ) ) } } |
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
.
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 return jsonMap } |
Now use TaskJsonView in TaskController. Add the following methods to TaskController.
1 2 3 4 5 |
@ResponseBody @GetMapping(produces = arrayOf("application/json")) fun listJson(): Map<String, Any?> { return TaskJsonView.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.
1 |
{"data":{"tasks":[{"id":1,"name":"First","created_at":"2017-11-17 10:56:35.555","updated_at":"2017-11-17 10:56:35.555"},{"id":2,"name":"Second","created_at":"2017-11-17 10:56:40.812","updated_at":"2017-11-17 10:56:40.812"},{"id":3,"name":"Third","created_at":"2017-11-17 10:56:43.102","updated_at":"2017-11-17 10:56:43.102"}]}} |
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 |
1 2 3 4 5 6 7 |
package com.example.myapp.presentation.layout object LayoutJsonView { fun success(data: Map<String, Any?>?): Map<String, Any?> { return mapOf("data" to data) } } |
And change list
method in TaskJsonView object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun list(taskList: List<Task>): Map<String, Any?> { return LayoutJsonView.success( mapOf( "tasks" to taskList.map { mapOf( "id" to it.id, "name" to it.name, "created_at" to it.createdAt?.toString(), "updated_at" to it.updatedAt?.toString() ) } ) ) } |
Continues to Kotlin 1.2.0 + Spring: create Web Application (4 of 4).