Jackson adds backslash in json

后端 未结 8 1079
伪装坚强ぢ
伪装坚强ぢ 2020-12-31 00:55

I\'m building REST service on Jersey and using Jackson to produce JSON from java classes of my model. Model with absolutely simple values, I think

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-31 01:21

    If you are using Spring and the @ControllerAdvice for JSONP, then create a wrapper for the JSON string and use @JsonRawValue on the property. The JSONP @ControllerAdvice will not wrap a String response, it needs an Object.

    public class JsonStringResponse {    
        @JsonValue
        @JsonRawValue
        private String value;
    
        public JsonStringResponse(String value) {
            this.value = value;
        }
    }  
    
    @GetMapping
    public ResponseEntity getJson() {
        String json = "{"id":2}";
        return ResponseEntity.ok().body(new JsonStringResponse(json));
    }
    
    
    @ControllerAdvice
    public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice {
        public JsonpControllerAdvice() {
            super("callback");
        }
    }
    

    Response is a json object {"id":2}
    If there is a callback parameter the response is callbackparameter({"id":2});

提交回复
热议问题