我正在使用gson库将数据序列化为json格式的字符串。当我在服务器上收到json消息时,我得到一个Unicode字符的问号。例如,我从android客户端发送以下内容:

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

但是服务器将其接收为:
{"message_content":"This is a test message: ???? ??????"}

代码:
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);
    }
}

最佳答案

我调试后发现HTTP帖子不支持UTF-8。关注此帖子:Android default charset when sending http post/put - Problems with special characters

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

07-27 19:27