简体   繁体   中英

Json response character encoding in Play Framework

I am having a problem and I need your help.

I am working in a server with Play Framework v1.2.4 in java that I use for my mobile app, and I have a problem in the Json response.

I have always use the views for enconding my Json response, but I have realized that when I use a special character (like ñ, \\n, á, é, etc) there is a problem and my mobile app have a wrong run.

Here is the code:

{
  "id":${data[0]},

  "messages": 
  [
      #{list items:data[1], as:'message'}
      {           
           "text":"${message.text}"
      }${message_isLast ? '' : ','
}#{/list}
 ] }

I have tried to do it with a java method to parse the response correctly instead of in the .json view, and it is ok. That is the code:

JsonObject jsonOut = new JsonObject(); 
jsonOut.addProperty("id",conversation.id); 
JsonArray jsonArray = new JsonArray();   

for(int i = 0; i < conversation.messages.size; i++)  {
    Message message = conversation.messages.get(i);
    JsonObject jsonMessage = new JsonObject();
    jsonMessage.addProperty("text", message.text);
    jsonArray.add(jsonMessage); 
}

jsonOut.add("messages", jsonArray); 

renderText(jsonOut);

My question is if I can do something in the view for parsing the variables correctly to json format without doing manually, because I have a lot of responses that I have to change.

Using templates for rendering JSON strings is... bad (and here I should just finish my answer, anyway...).

JSON serializers usually takes care about proper quotes, escapes special chars, honors types, encodes characters (if required) etc... As I can see your template DOESN'T do that.

With templates you need to do everything yourself, and if you don't know JSON specification perfectly, you are convicted to fail. It's not just like pasting ${message.text} in proper place...

In other words: your second approach will be always better than first.

The default encoding for JSON is UTF-8. The default encoding for Java is locale dependant.

You need to make sure that the JVM you are running Play on is also running UTF-8 as Charset.defaultCharset().

Both the compiler and the editor should have their encoding set to "UTF-8". The Play Framework and JSON use already UTF-8. Properties files should be \\u.... encoded. The error probably lies in non-Java files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM