5

我正在使用 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);
    }
} 
4

1 回答 1

5

我调试了一下,发现HTTP post不支持UTF-8。关注这篇文章:发送 http post/put 时的 Android 默认字符集 - 特殊字符问题

httpPost.setEntity(new StringEntity(body, HTTP.UTF_8));
于 2013-03-17T08:02:59.497 回答