2017-04-12 18 views
0

我能够从一个自定义的Java对象没有问题返回JSONP(以下这样:http://www.concretepage.com/spring-4/spring-4-mvc-jsonp-example-with-rest-responsebody-responseentity),但是当我尝试返回一个字符串withing的JSONP包装功能消失春天 - 返回字符串或JSONObject的入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错误。有任何想法吗?

回答

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启动:

<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> 
+0

我tr ied,但是当我返回JSONObject时,响应是406错误代码 – EsteBusta

+0

当我的类路径中没有'JsonpAdvice'类时,我得到了同样的错误。一旦我做了,我开始得到500错误,因为我没有配置Spring来序列化JSONObject。所以我转向了HashMap,它很容易转换成Json。该示例具体声明了该类型。我会更新我的答案来包含这一点。 – James

+0

谢谢,实际上切换到HashMap是我用它的方式,我再搜索一下,并意识到JSONObject无法序列化,就像你提到的,谢谢! – EsteBusta