簡體   English   中英

使用 feign 客戶端將枚舉列表轉換為 Spring @RequestParam 的字符串列表

[英]Convert List of Enums to List of String for Spring @RequestParam using feign client

我有一個枚舉 class 如下:

ONE("1", "Description1"),
TWO("2", "Description2");

String value;
String description;
MyEnum(String value, String description) {
    this.value  = value;
    this.description = description;
}

@Override
public String toString() {
    return this.value;
}
    
@JsonValue
public String value() {
    return this.value;
}

我正在與之交互的 API 需要一個字符串類型的參數,並且值可以用逗號分隔。

例如: api.com/test?param1=1,2我用 url api.com/test配置了一個 feign 客戶端然后創建了一個類似 POJO

public class POJO {
    private List<MyEnum> param1;
}

在我的假裝客戶中,我有:

@RequestMapping(method = RequestMethod.GET)
MyResponse getResponse(@SpringQueryMap POJO request);

在通過某些 Spring 方法進行 API 調用之前,是否可以以某種方式將枚舉列表轉換為字符串列表?

截至目前,當我傳遞一個枚舉列表時,它只考慮此列表中的最后一個枚舉。

更新:我使用@JsonSerialize(converter=abc.class) 注釋了要轉換為列表的屬性。 但是@SpringQueryMap 似乎並不尊重該序列化..

是的,您需要創建一個攔截器並在該方法中進行映射。 這個話題可能適合你。

Spring - 在調用控制器方法之前執行代碼

原來@JsonSerialize 沒有與@SpringQueryMap 一起工作所以我必須添加一個攔截器。

像這樣:

public class MyInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        if(requestTemplate.queries().containsKey("param1")) {
            requestTemplate.query("param1", convert(requestTemplate.queries().get("param1")));
        }
    }
    //convert list to a string
    public String convert(Collection<String> values) {
       final String s = String.join(",", values.stream().map(Object::toString).collect(Collectors.toList()));
       return s;
    }
}

然后在我的 Feign 配置 class 中添加了這個:

@Bean
public MyInterceptor myInterceptor() {
    return new MyInterceptor();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM