6

I am recieving a JSON object which is comes to me as a String from the front end and I want spring-boot to parse it into a Map for me.

I've tried @RequestHeader("header-name") Map header and @RequestHeader Map header but both give me a map of all the headers instead of the one I'm target which contains the JSON.

public ResponseEntity<MyObject> getStuff(@RequestHeader("My-Header") Map myHeaderJSON)

I expect the variable myHeaderJSON string to be parsed into a Map by Spring. Is there any way to achieve this? To have spring-boot parse a String into a JSON or Map for me?

2 Answers 2

3

if you want a single http request header to be "injected" into your controller method (as an argument) by Spring try it this way:

@RequestMapping("/your-path")
public ResponseEntity<MyObject> getStuff(@RequestHeader("My-Header") String jsonValue) {
   //...
}

also see here: https://www.viralpatel.net/spring-requestheader-example/

you can also try to implement a custom converter, see here for an example:

https://stackoverflow.com/a/50996349/150623

the way to go would be to use an ObjectMapper instance from the Jackson lib to convert the JSON string to a java.util.Map object...

could work this way (not tested though):

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

@Component
public class JsonToMapConverter implements Converter<String, Map<String,String>> {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Map<String, String> convert(final String json) {
        try {
           return objectMapper.readValue(json, Map.class);
        } catch (IOException e) {
           //handle exception...
        }
    }
}

don't forget to add Jackson to your dependencies, e.g. in Maven:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>
Sign up to request clarification or add additional context in comments.

1 Comment

Any way to avoid using String and go straight to a Map?
2

No, you will need to de-serialise it yourself.

From the spring docs:

If the method parameter is Map<String, String>, MultiValueMap<String, String>, or HttpHeaders then the map is populated with all header names and values.

It will not extract and deserialise json from the map, instead you will need to do something like:

public ResponseEntity<MyObject> getStuff(@RequestHeader Map myHeader) { 
    String json = myHeader.get("My-Header");
    MyClass myClass = objectMapper.readValue(json, MyClass.class);

    ... 
}

1 Comment

Thank you. I ended up doing it like this!

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.