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.

SpringのRest Templateで配列形式のJsonを取得するときの対応

Posted at

概要

SpringBootで外部のAPIからデータを取得する際に、Rest Templateを使うことがあると思います。Rest Templateの使い方についてはKotlin + Rest TemplateでのHttpリクエスト(GET編)の記事を参照頂きたいのですが、今回はレスポンスが配列形式で来た場合にどのように対応したらよいか書きます。

前提

  • 実装の言語はKotlinを前提とします。
  • レスポンスはJsonを前提とし、以下のような配列形式で返ってくるものとします。
sample.json
[
  {
    "id": 1
    "name": "test1",
  },
  {
    "id": 2
    "name": "test2",
  },
]

対応

一度テキストで取得してからJsonをパースしても良いのですが、出来ることならObjectでレスポンスを取得したいです。配列形式のJsonをObjectでどう読み込んだら良いかとなると、StackOverflowのKotlin call java method with Class argumentに色々と対応方法が書いてあります。以下の通り、個人的にはArrayでくるんで受け取る方法が一番簡潔に書けるかなと思います。

sample.kt
return restTemplate.getForObject(uri, Array<SampleObject>::class.java).toList()
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?