Kotlin как сохранить каждую строку в объектах класса? - PullRequest
0 голосов
/ 20 марта 2020

Список получаю из API. И я разделил это на линии. Я не уверен, как я могу сохранить каждую строку в классе объектов? Не могли бы вы помочь мне? [введите описание изображения здесь] [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)

1 Ответ

0 голосов
/ 20 марта 2020

Вы должны создать переменную для хранения 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)
...