Aditya Ekbote
Aditya Ekbote

Reputation: 1553

Spring boot decode POST request body

I have a spring boot application which has some POST API's. Consumer of API's is doing UTF-8 encoding on json values. Below is example.

{
    "id": 1,
    "name" "ABCD XYZ"
}

When client send above request, I am receiving,

{
    "id": 1,
    "name" "ABCD%20XYZ"
}

Please note "ABCD XYZ" is being replaced to "ABCD%20XYZ". Now I want to decode these values before it reaches my controller class. Is there a way where I can access this request body and change it by decoding values?

Upvotes: 0

Views: 1442

Answers (1)

crizzis
crizzis

Reputation: 10726

The way your client sends data is... peculiar.

However, you can use @JsonDeserialize(using = UrlEncodedDeserializer.class) on top of your DTO's name property, where UrlEncodedDeserializer could be implemented as follows:

public class UrlEncodedDeserializerextends StdDeserializer<String> {

@Override
    public String deserialize(JsonParser jp, DeserializationContext ctxt) 
      throws IOException, JsonProcessingException {
        return UrlEncoder.decode(jp.getValueAsString(), DefaultCharsets.UTF_8);
    }

}

If you want to decode all strings this way, you can register the serializer as part of a Jackson Module instead.

Upvotes: 1

Related Questions