【问题标题】:Spring - Return String or JSONObject into JSONPSpring - 将字符串或 JSONObject 返回到 JSONP
【发布时间】:2017-09-08 18:14:07
【问题描述】:

我能够毫无问题地从自定义 java 对象返回 JSONP(如下:http://www.concretepage.com/spring-4/spring-4-mvc-jsonp-example-with-rest-responsebody-responseentity),但是当我尝试使用 JSONP 返回字符串时,包装函数消失了

我在做什么:

  @RequestMapping(value ="/book", produces = {MediaType.APPLICATION_JSON_VALUE, "application/javascript"})
  public @ResponseBody ResponseEntity<String> bookInfo() {
    JSONObject test = new JSONObject();
    test.put("uno", "uno");
    return new ResponseEntity<String>(test.toString(), HttpStatus.OK);
}   

调用服务:

http://<server>:port//book?callback=test

返回:

{"uno":"uno"}

预期结果:

test({"uno":"uno"})

还尝试直接返回 JSONObject ResponseEntity.accepted().body(test);,但出现 406 错误。有什么想法吗?

【问题讨论】:

    标签: java json spring jsonp


    【解决方案1】:

    错误看起来像来自this example 的类JsonpAdvice,不适用于请求映射。

    @ControllerAdvice
    public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
        public JsonpAdvice() {
            super("callback");
        }
    }
    

    我使用了 HashMap,因为它在这里有类似的用途,而且 HashMap 在这个例子中使用起来更直接:

    @RequestMapping(value="/book", produces=MediaType.APPLICATION_JSON)
    public ResponseEntity<Map> bookInfo() {
        Map test = new HashMap();
        test.put("uno", "uno");
        return ResponseEntity.accepted().body(test);
    } 
    

    这为我提供了结果:

    // http://localhost:8080/book?callback=test
    
    /**/test({
      "uno": "uno"
    });
    

    我使用的是 Spring Boot:

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jersey</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.0</version>
        </dependency>
    </dependencies>
    

    【讨论】:

    • 我试过了,但是当我返回 JSONObject 时,响应是 406 错误代码
    • 当我的类路径中没有 JsonpAdvice 类时,我遇到了同样的错误。一旦我这样做了,我就开始收到 500 个错误,因为我没有配置 Spring 来序列化 JSONObject。所以我切换到HashMap,它很容易转换为Json。该示例专门声明了类型。我将更新我的答案以包含此内容。
    • 谢谢,实际上切换到 HashMap 是我使用它的方式,我重新搜索了一下,发现 JSONObject 不能像你提到的那样序列化,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多