【发布时间】:2015-12-08 22:36:28
【问题描述】:
我有一个这样的响应对象:
public class TestResponse {
private final String response;
private final ErrorCodeEnum error;
private final StatusCodeEnum status;
// .. constructors and getters here
}
我正在使用 Gson 库对上面的类进行序列化,如下所示:
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
System.out.println(gson.toJson(testResponseOutput));
我得到的回复如下所示:
{
"response": "{\"hello\":0,\"world\":\"0\"}",
"error": "OK",
"status": "SUCCESS"
}
如您所见,"response" 字段中的我的 json 字符串正在转义。有什么办法可以让 gson 不要这样做,而是返回一个完整的响应,如下所示:
{
"response": {"hello":0,"world":"0"},
"error": "OK",
"status": "SUCCESS"
}
还有——如果我按照上面的方式做会有什么问题吗?
注意:我的 "response" 字符串将始终是 JSON 字符串,否则它将为空,因此我的 "response" 字符串中只有这两个值。在"response" 字段中,我可以有任何json 字符串,因为这个库正在调用一个可以返回任何json 字符串的rest 服务,所以我将它存储在一个字符串"response" 字段中。
【问题讨论】:
-
你找到这个问题的合适答案了吗?
-
@nickb 我想还没有。如果您有任何问题,请随时写一个答案。可能对我有帮助吗?
-
当然,你试过my answer below吗?它应该适用于任意 JSON!