1

I want to use this code to get some data from Rest API:

public Map<Integer, String> getCategoriesList() {

        Map<Integer, String> list = new HashMap<>();
        list.put(1, "Electronics");
        list.put(2, "Outdoor and Sports");
        list.put(3, "Home and Garden");
        list.put(4, "Home appliances");
        list.put(5, "Air conditioners and heaters");
        list.put(6, "IT accessories");
        list.put(7, "Photo and Video");
        list.put(8, "TV Video and Gaming");

        return list;
    }

@GetMapping("categories")
public ResponseEntity<List<String>> getCategoriesList() {

    return (ResponseEntity<List<String>>) categoriesService.getCategoriesList();
}

I get error: class java.util.HashMap cannot be cast to class org.springframework.http.ResponseEntity

What is the appropriate way to return this data as a response?

1 Answer 1

2

You cannot cast one type to another like that...try this

ResponseEntity type:

@GetMapping("categories")
public ResponseEntity<Map<Integer, String>> getCategoriesList() {
    return new ResponseEntity<Map<Integer,String>>(categoriesService.getCategoriesList(), HttpStatus.OK);
}

Without ResponseEntity wrapper

@GetMapping("categories")
@ResponseStatus(code = HttpStatus.OK)
public Map<Integer, String> getCategoriesList() {
    return categoriesService.getCategoriesList();
}

Since both types of map are known to jackson (I presume that's what you are using in spring for serialization/deserialization), no need to do anything more.

Reference: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html

Sign up to request clarification or add additional context in comments.

6 Comments

I get Cannot infer arguments
Well ... alright - you need to do the casting in this scenario -- but what do u want to achieve? Do you want to return hashmap (as per question) or list as per code?
I want to return a hashmap - key - value pairs.
however...you can just return Map from the method - you do not need to use ResponseEntity type - I've edit my answer
Is it a good practice to use ResponseEntity wrapper? What are the benefits?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.