Gson unicode string serialization not working

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

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

But the server gets it like:

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

The 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);
    }
} 
+5
source share
1 answer

I debugged and found that the HTTP message does not support UTF-8. Following this post: Android default character set when sending http post / put - Problems with special characters

httpPost.setEntity(new StringEntity(body, HTTP.UTF_8));
+4
source

All Articles