android - 如何使用 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));
先感谢您。
解决方案
你应该尝试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\""'}]}
推荐阅读
- symfony - 在注册控制器中捕获错误
- android - java.lang.IllegalStateException:无法为 android 执行方法:onClick
- c# - 调用 SetGestureConfig 方法会影响控件的 onmousemove 覆盖
- jquery - HTML 选择更改不适用于 jQuery 函数
- html - 如何水平扩展 CSS 家谱?
- javascript - Javascript 或 jQuery 根据值填充数据
- android-volley - RecyclerView 中的 Gson 请求
- python - 如何将前导零填充到时间列?
- javascript - 如何在客户端导入 socket.io - SOCKET.IO + NODE.JS
- firebase - 线程 1:EXC_BAD_ACCESS 尝试将图像上传到 Firebase