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