Search code examples
spring-bootclassobjectkotlinresttemplate

Kotlin how to save each line into Class Objects?


I receive List from API. And I divided it by lines. I'm not sure How I can save each line into class Objects? Could you help me? [enter image description here][1]

class RecordsList {


    @RequestMapping("/")
    fun receiveAll(): List<String>? {
        val restTemplate = RestTemplate()
        val url = "some URL // doesn't matter"
        val response = restTemplate.getForObject(url, String::class.java)

        var lines = response?.lines()
        lines?.forEach { line -> println(line)}
        return lines
    }
}

data class Record(var domain: String, var code: String, var link: String, var other: String)

Solution

  • You should create a variable to store an arrayList of Records.

    class RecordsList {
    
    
    @RequestMapping("/")
    fun receiveAll(): ArrayList<Record>? {
    
        // ArrayList to store the `Record`s
        var arrayListOfRecord: ArrayList<Record>? = arrayListOf()
    
        val restTemplate = RestTemplate()
        val url = "some URL // doesn't matter"
        val response = restTemplate.getForObject(url, String::class.java)
    
        var lines = response?.lines()
    
        // For each line in the response create a Record object and add it to the 
        // `arrayListOfRecord`s
        lines?.forEach { line -> 
            arrayListOfRecord?.add(
                Record(
                    domain = line.domain,
                    code = line.code,
                    link = line.link,
                    other = line.other
                )
            )
        }
        return arrayListOfRecord 
        }
    }
    
    data class Record(var domain: String, var code: String, var link: String, var other: String)