在Retrofit 2和Gson中遇到特殊字符的问题

3
我正在尝试从网络服务获取一个 JSON 列表。服务器返回的 JSON 字符串如下所示: [{"categoryName":"政治"},{"categoryName":"经济"},{"categoryName":"文化"},{"categoryName":"体育"}] 问题在于如何将其转换成 POJO。特殊字符(í)显示为“Pol�tica”。 这是 Retrofit 调用函数:
  @GET("categories")
  public Call<List<CategoryPojo>> getCategorias(@Query("sitename") String site)

这是回调函数:

    Call<List<CategoryPojo>> call = restservice.getApiService().getCategorias(medio);

    try {
        call.enqueue(new Callback<List<CategoryPojo>>() {
            @Override
            public void onResponse(Call<List<CategoryPojo>> call, Response<List<CategoryPojo>> response) {
                List<CategoryPojo> categories = response.body();
                if (listener != null)
                    listener.onDataLoaded(categories);
            }

            @Override
            public void onFailure(Call<List<CategoryPojo>> call, Throwable throwable) {
                   Log.e("Retrofit Error", throwable.getMessage());

            }
        });

这是一个POJO:

public class CategoryPojo implements Serializable{

    public CategoryPojo() { }

    @SerializedName("categoryName")
    private String name;

    public String getName()
    {
      return this.name;
    }


 }

Web服务请求的结果(在浏览器中输出)为:

[{"categoryName":"Política"},{"categoryName":"Economía"},{"categoryName":"Cultura"},{"categoryName":"Deportes"},{"categoryName":"Salud"},{"categoryName":"Ciencia y Tecnología"},{"categoryName":"Medio Ambiente"},{"categoryName":"Medios"},{"categoryName":"Militar e Inteligencia"},{"categoryName":"Sociedad"}]

所以,返回的JSON编码很好...我认为可能是由于Retrofit读取响应的方式所致。我正在使用Retrofit-2.0.2、Gson-2.6.1、Converter-Gson-2.0.2、Okhttp-3.2.0。可以帮忙吗?谢谢。

那个输出到底在哪里呢?你是在将变量存储输出后,记录变量本身吗? - Daniel
@Jesse:嗯,调试器(Android Studio)的原始响应将Content-type设置为application/json。 - user6361891
@DanielK:输出是在Chrome浏览器中向WS发出请求的结果(您指的是正确的类别数组吗?)我不理解第二个问题...请向我解释一下。 - user6361891
@user636189,我在想这个 it's appear like "Pol�tica" 是不是来自你的 logcat。如果你在浏览器中尝试请求,它会返回 Política,对吗? - Daniel
@DanielK,没错。 - user6361891
显示剩余5条评论
1个回答

0
你应该检查响应头中的 Content-type。查找 charset 值并尝试在后端更改为 application/json;charset=UTF-8。这对我有用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接