【问题标题】:Decode response body from feign client to MyObject将 feign 客户端的响应正文解码为 MyObject
【发布时间】:2021-01-25 22:04:24
【问题描述】:

我已经创建了一个 Feign 客户端 StorageClient,如下所示:

@Headers(HttpHeaders.ACCEPT + ": " + MediaType.APPLICATION_JSON_UTF8_VALUE)
interface StorageApi {
    @RequestLine("GET /api/v1/files/{fileId}")
    fun getFileMeta(@Param("fileId") fileId: Long): Response
}
@Service
class StorageClient(private val storageApi: StorageApi) {
    fun getFile(fileId: Long): StorageFile = storageApi.getFileMeta(fileId)
}

除了StorageClient客户端,getFileMeta()方法(接口StorageApi)也用于检查状态(方法isFileExists()):

fun isFileExists(fileId: Long): Boolean = storageApi.getFileMeta(fileId).status() != 404

由于这个原因,我不能明确地写:

@RequestLine("GET /api/v1/files/{fileId}")
fun getFileMeta(@Param("fileId") fileId: Long): StorageFile

如何解码响应正文,以便可以从 getFile()StorageClient 类)方法返回 StorageFile 类型的对象?或者也许有一些方法可以同时处理收到的Responsestatus 及其body

【问题讨论】:

    标签: spring-boot rest kotlin response feign


    【解决方案1】:

    这个答案有点晚了,你可以使用Jackson等JSON反序列化器手动解码body:

    import com.fasterxml.jackson.databind.ObjectMapper
    import org.apache.commons.io.IOUtils
    
    val json = IOUtils.toString(response.body().asInputStream(), Charsets.UTF_8)
    val storageFile = ObjectMapper().readValue(json, StorageFile::class.java)
    

    确保将 Jackson 添加为依赖项。例如,如果您使用的是 maven,则在您的 pom.xml 中:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>..</version>
    </dependency>
    

    这里有关于 Jackson 的深入教程:https://www.baeldung.com/jackson-object-mapper-tutorial


    重要通知:完成后请务必致电response.close()。否则会导致资源泄露。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-25
      • 2021-12-08
      • 2020-01-02
      • 2018-02-12
      • 2019-05-17
      • 2015-12-10
      • 1970-01-01
      • 2022-07-09
      相关资源
      最近更新 更多