Spring RESTFul客户端 - RestTemplate

时间:2016-03-29 18:37:19

标签: spring resttemplate

我使用Resttemplate class获取all User个对象。但是当我在客户端运行Main然后出现错误时,请让我知道如何解决它?

  

线程中的异常" main"   org.springframework.http.converter.HttpMessageNotReadableException:   无法读取JSON:无法反序列化实例   edu.java.spring.service.user.model.User出自START_ARRAY令牌   [资源:   sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@7d70d1b1;   line:1,column:1];嵌套异常是   com.fasterxml.jackson.databind.JsonMappingException:不能   反序列化edu.java.spring.service.user.model.User的实例   [来源:START_ARRAY令牌   sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@7d70d1b1;   line:1,column:1] at   org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:228)     在   org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.read(MappingJackson2HttpMessageConverter.java:220)     在   org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:95)     在   org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:549)     在   org.springframework.web.client.RestTemplate.execute(RestTemplate.java:502)     在   org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:239)     在   edu.java.spring.service.client.RestClientTest.getUsers(RestClientTest.java:57)     在   edu.java.spring.service.client.RestClientTest.main(RestClientTest.java:40)   引起:com.fasterxml.jackson.databind.JsonMappingException:可以   不反序列化edu.java.spring.service.user.model.User的实例   在[来源:来自:START_ARRAY标记   sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@7d70d1b1;   line:1,column:1]

此处归档RestClientTest.java

public class RestClientTest {

    public static void main(String[] args) throws IOException{
        List<User> users = getUsers();
        for (int i = 0; i < users.size(); i++) {
            System.out.println("Rest Response" + loadUser(users.get(i).getUserName()));
        }

    }
    public static List<User> getUsers(){
        String uri = new String("http://localhost:8080/rest/user/list");
        RestTemplate rt = new RestTemplate();
        return (List<User>) rt.getForObject(uri,User.class);
    }

此处归档UserRestServiceController.java

@Controller
public class UserRestServiceController {
    @Autowired
    public  UserDao userDao;
    @RequestMapping(value = "/rest/user/list", produces = MediaType.APPLICATION_JSON_VALUE,method = RequestMethod.GET)
    public @ResponseBody List<User> getUsers(){
        return userDao.listUsers();
    }

1 个答案:

答案 0 :(得分:3)

我认为其余的方法是将List<User>个对象发送给您,但您尝试使用以下代码中的User.class解析它:rt.getForObject(uri,User.class);。尝试类似rt.getForObject(uri,List.class);的内容。