首页 > 解决方案 > 如何使用 Retrofit2 和 Gson 转换器防止在序列化过程中转义

问题描述

我陷入了沉思,并尽力寻找并提出可能的解决方案。我已经尝试了大多数可能与我想要实现的目标相关的答案,但仍然没有运气。

因此,为了详细说明我的问题,我收到了来自 API 的回复

{
    "profileList": [
        {
          "id": "7mmfHGLc0MGtZeQNno/WFqDjlAPj26CS",
          "name": "Alexandria Victoria Maxene Kluber  van de Gr\\\"oot\""
         }
       ]
}

我想要实现的是在不转义值的情况下获取“名称”字段值。因为在我当前的设置中,反序列化过程后我从该响应中得到的是Alexandria Victoria Maxene Kluber van de Gr\"oot""

我让我的 Retrofit 处理 API 请求和响应,这就是我得到的,我目前不想因为特定原因撕掉我的处理程序,但我希望有人能指出我正确的方向。这是我的改造生成器代码:

Gson gson = new GsonBuilder()
                        .disableHtmlEscaping()
                        .create();
      m_builder = new Retrofit.Builder()
                  .baseUrl(url)
                  .addConverterFactory(GsonConverterFactory.create(gson));

先感谢您。

标签: androidgsonretrofit2

解决方案


你应该尝试JsonPrimitive在你的POJO. 请参见下面的示例:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonPrimitive;

import java.io.File;
import java.io.FileReader;
import java.util.List;

public class GsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        Gson gson = new GsonBuilder().create();

        System.out.println(gson.fromJson(new FileReader(jsonFile), Profiles.class));
    }
}

class Profiles {

    private List<Profile> profileList;

    // getters, setters, toString
}

class Profile {

    private String id;
    private JsonPrimitive name;

    // getters, setters, toString
}

上面的JSON有效载荷打印示例:

Profiles{profileList=[Profile{id='7mmfHGLc0MGtZeQNno/WFqDjlAPj26CS', name='"Alexandria Victoria Maxene Kluber  van de Gr\\\"oot\""'}]}

推荐阅读