【问题标题】:Serialize Feign Json Response to object序列化 Feign Json 对对象的响应
【发布时间】:2021-04-22 08:52:25
【问题描述】:

我收到了来自 Feign 客户端的以下 Json 响应:

{
  "maxResults": 1,
  "total": 5,
  "isLast": false,
  "values": [
    {
      "id": 37,
      "self": "https://your-domain.atlassian.net/rest/agile/1.0/sprint/23",
      "state": "active",
      "name": "sprint 1",
      "goal": "sprint 1 goal"
    }
  ]
}

假客户:

@FeignClient(name = "jira")
public interface JiraFeignClient {

    @GetMapping("/rest/agile/1.0/board/{boardId}/sprint?state=active&maxResults=1")
    ActiveSprintResponse getActiveSprint(@PathVariable String boardId);
}

我想定义 ActiveSprintResponse 类,以便获得与 json 响应的“值”属性(我只对这些属性感兴趣)相关的信息,但我不明白如何轻松代表它。 我对属性“maxResults”、“total”等没有任何问题……但是如何轻松解压“values”呢?我可以假设值数组中始终只有一个元素。

我试过这样定义它,但它显然不起作用:

public class ActiveSprintResponse {

    private final String id;
    private final String self;
    private final String name;
    private final String goal;

    public ActiveSprintResponse(String id, String self, String name, String goal) {
        this.id = id;
        this.self = self;
        this.name = name;
        this.goal = goal;
    } 
}

【问题讨论】:

    标签: json response feign


    【解决方案1】:

    您需要定义一个代表根 JSON 对象的类。您可以为 List 类型的values 定义一个属性,然后:

    public class ActiveSprintResponseList {
    
      private List<ActiveSprintResponse> values;
    
      // (Other fields omitted for simplicity)
     
      public void setValues(List<ActiveSprintResponse> values) {
        this.values = values;
      }
    
      public List<ActiveSprintResponse> getValues() {
        return values;
      }
    }
    

    然后你需要将该类声明为返回类型:

    @FeignClient(name = "jira")
    public interface JiraFeignClient {
    
        @GetMapping("/rest/agile/1.0/board/{boardId}/sprint?state=active&maxResults=1")
        ActiveSprintResponseList getActiveSprint(@PathVariable String boardId);
    }
    

    并在调用方使用它:

    ActiveSprintResponseList response = client.getActiveSprint(..);
    List<ActiveSprintResponse> values = response.getValues();
    // work with values
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      相关资源
      最近更新 更多