How to consume Page response using Spring RestTemplate

前端 未结 7 895
感动是毒
感动是毒 2020-12-02 16:42

I\'m using spring data (mongoDb) and I\'ve got my repository:

public interface StoriesRepository extends PagingAndSortingRepository {}
<         


        
7条回答
  •  星月不相逢
    2020-12-02 17:35

    I know this thread is a little old, but hopefully someone will benefit from this.

    @Ali Dehghani's answer is good, except that it re-implements what PageImpl has already done. I considered this to be rather needless. I found a better solution by creating a class that extends PageImpl and specifies a @JsonCreator constructor:

    import com.fasterxml.jackson.annotation.JsonCreator;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.company.model.HelperModel;
    import org.springframework.data.domain.PageImpl;
    import org.springframework.data.domain.PageRequest;
    
    import java.util.List;
    
    public class HelperPage extends PageImpl {
    
        @JsonCreator
        // Note: I don't need a sort, so I'm not including one here.
        // It shouldn't be too hard to add it in tho.
        public HelperPage(@JsonProperty("content") List content,
                          @JsonProperty("number") int number,
                          @JsonProperty("size") int size,
                          @JsonProperty("totalElements") Long totalElements) {
            super(content, new PageRequest(number, size), totalElements);
        }
    }
    

    Then:

    HelperPage page = restTemplate.getForObject(url, HelperPage.class);
    

    This is the same as creating a CustomPageImpl class but allows us to take advantage of all the code that's already in PageImpl.

提交回复
热议问题