Java 如何要求gson避免在json响应中转义json?

Java 如何要求gson避免在json响应中转义json?,java,json,gson,Java,Json,Gson,我有这样一个响应对象: public class TestResponse { private final String response; private final ErrorCodeEnum error; private final StatusCodeEnum status; // .. constructors and getters here } { "response": {"hello":0,"world":"0"}, "error"

我有这样一个响应对象:

public class TestResponse {

    private final String response;
    private final ErrorCodeEnum error;
    private final StatusCodeEnum status;

    // .. constructors and getters here
}
{
  "response": {"hello":0,"world":"0"},
  "error": "OK",
  "status": "SUCCESS"
}
我正在使用Gson库序列化上述类,如下所示:

Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
System.out.println(gson.toJson(testResponseOutput));
{
  "response": "{\"hello\":0,\"world\":\"0\"}",
  "error": "OK",
  "status": "SUCCESS"
}
我得到的回复如下所示:

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不要这样做,而是像这样返回完整的响应:

public class TestResponse {

    private final String response;
    private final ErrorCodeEnum error;
    private final StatusCodeEnum status;

    // .. constructors and getters here
}
{
  "response": {"hello":0,"world":"0"},
  "error": "OK",
  "status": "SUCCESS"
}
还有,如果我这样做有什么问题吗


注意:My
“response”
字符串将始终为JSON字符串,或者为空,因此在My
“response”
字符串中只有这两个值。在
“response”
字段中,我可以拥有任何json字符串,因为此库正在调用rest服务,该服务可以返回任何json字符串,因此我将其存储在字符串
“response”
字段中。

根据需要,您可以使用映射(或类似)或嵌套对象,而不是字符串。用这种方式表示它应该不会有问题,但在您的示例中,如果它是字符串,如果不转义双引号之类的字符,则会有问题。

您应该有一个嵌套对象

public class Response {
    private final Integer hello;
    private final String world;
}

public class TestResponse {
    private final Response response;
    private final ErrorCodeEnum error;
    private final StatusCodeEnum status;

    // .. constructors and getters here
}

如果
响应
字段可以是任意JSON,则需要:

  • 将其定义为任意JSON字段(通过将其定义为JSON层次结构的根,利用GSON中已经内置的JSON类型系统-)

  • 字符串
    字段转换为适当的JSON对象表示形式。为此,您可以使用GSON的类:

  • 应打印:

    {
      "response": {
        "hello": 0,
        "world": "0"
      }
    }
    
    它还应适用于任何有效的JSON:

    String responseJson = "{\"arbitrary\":\"fields\",\"can-be\":{\"in\":[\"here\",\"!\"]}}";
    JsonElement json = parser.parse(responseJson);
    System.out.println(gson.toJson(new TestResponse(json)));
    
    输出:

    {
      "response": {
        "arbitrary": "fields",
        "can-be": {
          "in": [
            "here",
            "!"
          ]
        }
      }
    }
    

    我知道这很古老,但只是在需要时添加了一个潜在的答案

    听起来您只是想返回响应而不转义。转义是一件好事,它将有助于防止安全问题,并防止JS应用程序因错误而崩溃

    但是,如果仍要忽略转义,请尝试:


    Gson Gson=new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().serializeNulls().create()

    添加简单类型适配器并使用jsonValue(value) gson 2.8.0

    第1版:

      @Test
    public void correctlyShow() {
        TestResponse2 src = new TestResponse2("{\"arbitrary\":\"fields\",\"can-be\":{\"in\":[\"here\",\"!\"]}}");
        Gson create = new GsonBuilder().registerTypeAdapter(String.class, ADAPTER).create();
    
        Stopwatch createStarted = Stopwatch.createStarted();
        String json2 = create.toJson(src);
        System.out.println(json2 + " correctlyShow4 " + createStarted.stop());
    }
    
    public class TestResponse2 {
        private final String response;
    
        public TestResponse2(String response) {
            this.response = response;
        }
    
        public String getResponse() {
            return response;
        }
    }
    
    private static final TypeAdapter<String> ADAPTER = new TypeAdapter<String>() {
        @Override
        public String read(JsonReader in) throws IOException {
            throw new UnsupportedOperationException("Unsupported Operation !!!");
        }
    
        @Override
        public void write(JsonWriter out, String value) throws IOException {
            out.jsonValue(value);
        }
    };
    
    @测试
    公屋{
    testresponse2src=newtestresponse2(“{\'arbitral\':\'fields\',\'can be\':{\'in\':[\'here\',\'!\']}”);
    Gson create=new GsonBuilder().registerTypeAdapter(String.class,ADAPTER).create();
    Stopwatch createStarted=Stopwatch.createStarted();
    字符串json2=create.toJson(src);
    System.out.println(json2+“correctlyShow4”+createStarted.stop());
    }
    公共类TestResponse2{
    私有最终字符串响应;
    公共TestResponse2(字符串响应){
    这个。反应=反应;
    }
    公共字符串getResponse(){
    返回响应;
    }
    }
    私有静态最终类型适配器=新类型适配器(){
    @凌驾
    公共字符串读取(JsonReader in)引发IOException{
    抛出新的UnsupportedOperationException(“不支持的操作!!!”);
    }
    @凌驾
    公共void write(JsonWriter out,字符串值)引发IOException{
    out.jsonValue(value);
    }
    };
    

    维斯里翁2号

    @Test
    public void correctlyShow() {
        TestResponse2 src = new TestResponse2("{\"arbitrary\":\"fields\",\"can-be\":{\"in\":[\"here\",\"!\"]}}");
    
        String json2 = new Gson().toJson(src);
        System.out.println(json2 + " correctlyShow4 ");
    }
    
    public class TestResponse2 {
        @JsonAdapter(value = AdapterStringJson.class)
        private final String response;
    
        public TestResponse2(String response) {
            this.response = response;
        }
    
        public String getResponse() {
            return response;
        }
    }
    
    private class AdapterStringJson extends TypeAdapter<String> {
        @Override
        public String read(JsonReader in) throws IOException {
            throw new UnsupportedOperationException("Unsupported Operation !!!");
        }
    
        @Override
        public void write(JsonWriter out, String value) throws IOException {
            out.jsonValue(value);
        }
    }
    
    @测试
    公屋{
    testresponse2src=newtestresponse2(“{\'arbitral\':\'fields\',\'can be\':{\'in\':[\'here\',\'!\']}”);
    字符串json2=new Gson().toJson(src);
    System.out.println(json2+“correctlyShow4”);
    }
    公共类TestResponse2{
    @JsonAdapter(值=AdapterStringJson.class)
    私有最终字符串响应;
    公共TestResponse2(字符串响应){
    这个。反应=反应;
    }
    公共字符串getResponse(){
    返回响应;
    }
    }
    私有类适配器StringJSON扩展了TypeAdapter{
    @凌驾
    公共字符串读取(JsonReader in)引发IOException{
    抛出新的UnsupportedOperationException(“不支持的操作!!!”);
    }
    @凌驾
    公共void write(JsonWriter out,字符串值)引发IOException{
    out.jsonValue(value);
    }
    }
    
    并不总是“你好”和“世界”。我正在从另一个服务获取响应字段中的JSON字符串。因此,在响应字段中,它可以是任何JSON字符串。因此,您需要找到一种将JSON字符串解析为对象的方法。也许这个链接可以帮助你。你找到这个问题的合适答案了吗?@nickb我想还没有。。如果你有什么问题,请随时写一个答案。。也许这能帮我一点忙?当然,你试过了吗?它应该适用于任意JSON!对我也有用。谢谢我在javadocs中看到了它,但它似乎没有解析,在源代码中也找不到任何对它的引用。这个被移除了吗?