Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Gson and encoding

I am using Umlauts (ä,ü,ö) in a Gson that I need to pass via Http Post Body.

Unfortuenately, my web app will return null if the Umlauts are not converted somehow, and they are not.

content-type is "application/json"

How do I tell Gson to encode the Umlauts properly (the Umlauts are in the values, not the keys)?

like image 646
cdbeelala89 Avatar asked Dec 19 '12 11:12

cdbeelala89


2 Answers

I had the same problem passing umlaut to a web service in JSON. The webserver could not decode correctly those characters. By configuring the HttpClient for UTF encoding the problem disappeared, here is my working code:

HttpParams httpParams = new BasicHttpParams();
HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);
HttpProtocolParams.setHttpElementCharset(httpParams, HTTP.UTF_8);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost request = new HttpPost(serverURL);
StringEntity str = null;
String jsonString = gson.toJson(yourdata);
str = new StringEntity(jsonString, HTTP.UTF_8);
request.setEntity(str);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
client.execute(request);
like image 110
Wizche Avatar answered Sep 25 '22 12:09

Wizche


You could try to set

charset=UTF-8

to force the encoding.

like image 21
Miguel Teixeira Avatar answered Sep 23 '22 12:09

Miguel Teixeira