RestTemplate:返回实体列表

时间:2018-05-26 08:32:53

标签: rest spring-mvc spring-boot resttemplate restful-architecture

有一个RestFull方法返回一个Menu对象列表

  <ion-toolbar color="narenji">
    <ion-segment color="light" [(ngModel)]="sellsegments" (ionChange)="onSegmentChanged($event)">
      <ion-segment-button *ngFor="let state of states" [value]="state.id">
        {{state.name}}
      </ion-segment-button>
    </ion-segment>
  </ion-toolbar>

<ion-content padding id="page2">

  <ion-slides [dir]="this.platform.dir()" #mySlider (ionSlideWillChange)="onSlideChanged($event)" (ionSlideDidChange)="onSlideChanged($event)">
    <ion-slide *ngFor="let state of states">
      <ion-list>
        <ion-item *ngFor="let city of cities?.cities" (click)="goToCat()">
          <ion-thumbnail item-left>
            <img [src]="'https://www.asasara.com/'+city.image_thumb">
          </ion-thumbnail>
          <h2 text-end>{{city.name}}</h2>
        </ion-item>
      </ion-list>
    </ion-slide>
  </ion-slides>

</ion-content>

但我不知道如何从RestTemplate获取它们,从ResponseEntity获取该类&gt;

public ResponseEntity<List<Menu>> getMenus() {
..
}

3 个答案:

答案 0 :(得分:3)

我一直在尝试提出一些通用方法来封装此类功能,并在我当前的项目中使用它。 最终,我找到了解决方法。

public static <T> List<T> getForList(RestTemplate restTemplate, String url, Class<T> cls, Object... uriVariables) {
    ObjectMapper mapper = new ObjectMapper();
    CollectionType type = mapper.getTypeFactory().constructCollectionType(List.class, cls);
    return restTemplate.<List<T>>exchange(url, HttpMethod.GET, null,
                ParameterizedTypeReference.forType(type), uriVariables)
        .getBody();
}

答案 1 :(得分:2)

尝试使用ParameterizedTypeReference

ResponseEntity<List<Menu>> response = restTemplate
       .exchange("URI", HttpMethod.GET, entity,  new ParameterizedTypeReference<List<Menu>>() {
 });

答案 2 :(得分:1)

尝试一下,对我来说,在春季用RestTemplate获取对象列表

    RestTemplate restTemplate = new RestTemplate();
    try {
        ResponseEntity<List<Claim>> claimResponse = restTemplate.exchange(
                uri, 
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<Claim>>() {});
        if(claimResponse != null && claimResponse.hasBody()){
            claims = claimResponse.getBody();
        }
    } catch (RestClientException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }