Thái Huỳnh Quang Thái Huỳnh Quang -4 years ago 257
reST (reStructuredText) Question

Cannot Receive UTF-8 format with String in LinkedHashMap when using RestTemplate

So I have problem with character encoding when receive data from restclient using restTemplate to send data. and this my example code:

This is my client code; I already receive data with UTF-8 encoding:

rest.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));

Map<String,Object> params = new HashMap<String,Object>();
params.put("modelname","character without utf-8");
MyModel oldModel = rest.postForObject(MYMODEL_SERVICE_URI + "/get", params, MyModel.class);//it return perfect model with utf-8 encoded
oldModel.setContent("Tôi muốn cập nhật model này với định dạng UTF-8");

MyModelWrapper wrapper = new MyModelWrapper();
wrapper.add(oldModel);
params.put("newmodel", wrapper);
Message message = rest.postForObject(MYMODEL_SERVICE_URI + "/update", params, Message.class);//class message contains the message back and the status of that message in boolean
System.out.println(message);


This is my service code

@RequestMapping(value="/update", method=RequestMethod.POST)
@ResponseBody
public Message update(@RequestBody Map<String, Object> params){
.....
LinkedHashMap<String,Object> map = (LinkedHashMap<String,Object>params.get("newmodel");
Iterator<String> iter = map.keySet().iterator();
String key = "";
while(iter.hasNext()){
key = iter.next();
System.out.println(map.get(key));//returned the string value is not in utf-8 format
//some method casting linkedhashmap to MyModel
}

....
return message;
}


And the return message of it is not in utf-8 encoding. So I need helps about encoding when receive object from rest-client.

Answer Source

Add consumes, produces to @RequestMapping with application/json;charset=UTF-8 and see

@RequestMapping(value="/update", method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_UTF8, produces=MediaType.APPLICATION_JSON_UTF8)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download