Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gson serialization of unicode string not working

I am using gson library to serialize my data into a json format string. When I receive the json message on the server I get a question mark for unicode characters. For example, I send the following from my android client:

{"message_content":"This is a test message: مرحبا أصدقاء"}

But the server receives it as:

{"message_content":"This is a test message: ???? ??????"}

Code:

import java.io.UnsupportedEncodingException;

import android.telephony.PhoneNumberUtils;

import com.google.gson.Gson;

import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;

public class TestMessage {

    @SerializedName("message_content")
    private String mMessageContent;

    public TestMessage(String messageContent) {

        try {
            byte[] utf8 = messageContent.getBytes("UTF-8");
            mMessageContent = new String(utf8, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            mMessageContent = messageContent;
        }
    }

    public String toJSON() {
        Gson gson = new GsonBuilder().create();
        return gson.toJson(this);
    }
} 
like image 477
ssk Avatar asked Mar 17 '13 07:03

ssk


1 Answers

I debugged and found that the HTTP post didn't support UTF-8. Followed this post: Android default charset when sending http post/put - Problems with special characters

httpPost.setEntity(new StringEntity(body, HTTP.UTF_8));
like image 61
ssk Avatar answered Sep 29 '22 07:09

ssk