我有一个这样的响应对象:
public class TestResponse {
private final String response;
private final ErrorCodeEnum error;
private final StatusCodeEnum status;
// .. constructors and getters here
}
Run Code Online (Sandbox Code Playgroud)
我正在使用Gson库序列化上述类,如下所示:
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
System.out.println(gson.toJson(testResponseOutput));
Run Code Online (Sandbox Code Playgroud)
我得到的响应如下所示:
{
"response": "{\"hello\":0,\"world\":\"0\"}",
"error": "OK",
"status": "SUCCESS"
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我在json "response"字段中的字符串被转义了。有什么办法可以让gson不要这样做,而是返回一个完整的响应,如下所示:
{
"response": {"hello":0,"world":"0"},
"error": "OK",
"status": "SUCCESS"
}
Run Code Online (Sandbox Code Playgroud)
而且-如果我按上述方式进行操作,是否有任何问题?
注意:我的"response"字符串将始终为JSON字符串或为null,因此我的"response"字符串中只有这两个值。在"response"field中,我可以有任何json字符串,因为此库正在调用rest服务,该服务可以返回任何json字符串,因此我将其存储在string "response"字段中。
如果您的response字段可以是任意JSON,则您需要:
将其定义为任意JSON字段(通过将其定义为JSON层次结构的根来利用GSON内置的JSON类型系统JsonElement)
public class TestResponse {
private final JsonElement response;
}
Run Code Online (Sandbox Code Playgroud)将String字段转换为适当的JSON对象表示形式。为此,您可以使用GSON的JsonParser类:
final JsonParser parser = new JsonParser();
String responseJson = "{\"hello\":0,\"world\":\"0\"}";
JsonElement json = parser.parse(responseJson); // Omits error checking, what if responseJson is invalid JSON?
System.out.println(gson.toJson(new TestResponse(json)));
Run Code Online (Sandbox Code Playgroud)这应该打印:
{
"response": {
"hello": 0,
"world": "0"
}
}
Run Code Online (Sandbox Code Playgroud)
它也应该适用于任何有效的JSON:
String responseJson = "{\"arbitrary\":\"fields\",\"can-be\":{\"in\":[\"here\",\"!\"]}}";
JsonElement json = parser.parse(responseJson);
System.out.println(gson.toJson(new TestResponse(json)));
Run Code Online (Sandbox Code Playgroud)
输出:
{
"response": {
"arbitrary": "fields",
"can-be": {
"in": [
"here",
"!"
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6935 次 |
| 最近记录: |