Skip to content
Advertisement

Java JSON String problem encoding Multipart

I’m developing a REST API that receives a MultipartFormDataInput object (org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput), this comes from a form-data Vue.js app. On the data field comes a json string that contains latin accent characters (á, é, í, ó, ú, ñ). When print the json data in Java I get this:

Original Json string

JavaScript

Json string received in Java

JavaScript

What can i do to receive the string with latin special characters?

My code (end point):

JavaScript

Implementation:

JavaScript

and pom dependency:

JavaScript

Advertisement

Answer

So in multipart, each body part is its own separate entity with its own separate content-type. If you don’t set the content-type for each part in the client request, it is assumed to be text/plain. In the case of RESTEasy implementation, it is text/plain; charset=ISO-8859-1.

InputPart.DEFAULT_CONTENT_TYPE_PROPERTY
If no content-type header is sent in a multipart message part “text/plain; charset=ISO-8859-1” is assumed.

A lot of clients are not able to set the content-type header for each part. So what you should do is set the content-type header for them. For this part, you want it to be application/json; chartset=utf-8. How you set the header is by getting the InputPart from the MultiPartFormDataInput. Instead of using the getFormDataPart() method, use the getFormDataMap() method to get a Map<String, List<InputPart>> return type. From there, get the InputPart and call InputPart#setMediaTye(), then you can get the data with one of the InputPart#getBody() variants. Something like (not tested):

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement