1.创建RestTemplate对象
RestTemplate restTemplate = new RestTemplate();
ResponseErrorHandler responseErrorHandler = new ResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return true;
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
};
restTemplate.setErrorHandler(responseErrorHandler);
2.调用get请求方法
String s = restTemplate.getForObject("http://localhost:8888/api4bms/migrate/getOfficeAccount?page=" + i + "&size=10", String.class);
3.json转化实体类
Migrater migraterResponseMsg = JacksonHelper.toParseObj(s, Migrater.class);
注意返回格式,json字符串格式和实体类必须一致
Migrater类
import com.ykhd.office.domain.resp.OfficeAccountDto;
import java.io.Serializable;
import java.util.List;
/**
* @author zhoufan
* @Date 2020/10/13
* json转化的实体类
*/
public class Migrater implements Serializable{
private int code;
private String msg;
List<OfficeAccountDto> data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<OfficeAccountDto> getData() {
return data;
}
public void setData(List<OfficeAccountDto> data) {
this.data = data;
}
}
JacksonHelper类
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Easy to use for Jackson
*/
public final class JacksonHelper {
private static ObjectMapper mapper = new ObjectMapper();
/**
* obj -> jsonStr
*/
public static String toJsonStr(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("json parse error!");
}
}
/**
* jsonStr --> obj
*/
public static <T> T toParseObj(String jsonStr, Class<T> clas) {
try {
return mapper.readValue(jsonStr, clas);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("json parse error!");
}
}
/**
* jsonStr --> list<obj>
*/
public static <T> List<T> toParseObjArray(String jsonStr, Class<T> clas) {
JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, clas);
try {
return mapper.readValue(jsonStr, javaType);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("json parse error!");
}
}
}