0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Kotlin] REST APIのレスポンスをメタデータでソートしたいとき

Last updated at Posted at 2021-06-17

やりたいこと

REST APIで以下のようなJSONで帰ってくるKotlinのコードがあったとします。

[{"name":"Taro", "age":"28", "createdAt":"2021/02/22 12:01:10"},
 {"name":"Hanako", "age":"28", "createdAt":"2021/02/22 15:10:39"},
 {"name":"Yoshi", "age":"44", "createdAt":"2021/02/23 00:39:44"}]

ResponseクラスにcreatedAtを含めずにでも、createdAtでソートする方法をメモっておきます。

createdAtを見せずにソート

Response.kt
data class Response(
        var name: String,
        var age: Int
) {
    @JsonIgnore
    var createdAt: LocalDateTime? = null
    constructor(user: User): this(
        name = user.name,
        age  = user.age
    ) {
        createdAt = user.createdAt
    }
}
```

```kotlin:sort.kt
fun sort(list: List<Response>) : List<Response> {
    return list.sortedBy { it.createdAt }
}
```

```json
[{"name":"Taro", "age":"28"},
 {"name":"Hanako", "age":"28"},
 {"name":"Yoshi", "age":"44"}]
```
トに限らず、デタクラスに対するメタデタ的なものを用いてロジックを組みたいときなど、`@JsonIgnore`が結構重宝します。

# createdAtが見えてしまう形でソ

```kotlin:Response.kt
data class Response(
        var name: String,
        var age: Int,
        var createdAt: LocalDateTime
) {
    constructor(user: User): this(
        name = user.name,
        age  = user.age,
        createdAt = user.createdAt
    )
}
```
または以下もダメです。

```kotlin:Response.kt
data class Response(
        var name: String,
        var age: Int
) {
    var createdAt: LocalDateTime? = null
    constructor(user: User): this(
        name = user.name,
        age  = user.age
    ) {
        createdAt = user.createdAt
    }
}
```

```kotlin:sort.kt
fun sort(list: List<Response>) : List<Response> {
    return list.sortedBy { it.createdAt }
}
```

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?