0

I'm using RestTemplate class to get All user but when i run Main in Client then occur error, i don't know why ???

Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to edu.java.spring.service.user.model.User at edu.java.spring.service.client.RestClientTest.main(RestClientTest.java:33)

Here file 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,List.class);
    }

    public static String loadUser(String username) throws IOException {
        String url = "http://localhost:8080/rest/user/json/" + username;

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Accept", "application/json");
        InputStream stream = con.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(stream));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();

    }

Here file UserRestServiceController.java

   @Controller
public class UserRestServiceController {
    @Autowired
    public  UserDao userDao;
    @Autowired
    public View jsonTemplate;
    @RequestMapping(value = "/rest/user/list", produces = MediaType.APPLICATION_JSON_VALUE,method = RequestMethod.GET)
    public @ResponseBody List<User> getUsers(){
        return userDao.listUsers();
    }
    @RequestMapping(value="/rest/user/json/{username}")
    public ModelAndView loadUser(@PathVariable("username")String name){
        return new ModelAndView(jsonTemplate,"data",userDao.loadUser(name));
    }
Dat Pham
  • 147
  • 1
  • 2
  • 13

1 Answers1

-1

I believe the following method is not returning as you expect:

rt.getForObject(uri,List.class);

Take a look at this question as it might help you also fix your error. ClassCastException: RestTemplate returning List instead of List

Community
  • 1
  • 1