如何在Spring Boot上返回JSONObject?

时间:2018-10-02 15:59:07

标签: java spring-boot

我有一个正在调用另一个Web服务的Web服务:

String restServiceUrl = "https://api.coinmarketcap.com/v2/ticker/?start" + start + "&limit=" + limit + "&sort=" + sort;
String coinmarketcapJSONString = new RestTemplate().getForObject(restServiceUrl, String.class);
JSONObject coinmarketcapJSONObject = new JSONObject(coinmarketcapJSONString).getJSONObject("data");
JSONArray coinmarketcapJSONArray = coinmarketcapJSONObject.names();

我的 coinmarketcapJSONObject 看起来像这样:

{"1":{"symbol":"BTC","circulating_supply":1.7300962E7,"last_updated":1538495424,"total_supply":1.7300962E7,"name":"Bitcoin","max_supply":2.1E7,"rank":1,"id":1,"website_slug":"bitcoin","quotes":{"USD":{"percent_change_1h":-0.1,"market_cap":1.13449548429E11,"percent_change_24h":-0.12,"price":6557.41272818,"volume_24h":3.85360400868166E9,"percent_change_7d":2.1}}},"1027":{"symbol":"ETH","circulating_supply":1.02322624E8,"last_updated":1538495440,"total_supply":1.02322624E8,"name":"Ethereum","max_supply":null,"rank":2,"id":1027,"website_slug":"ethereum","quotes":{"USD":{"percent_change_1h":-0.21,"market_cap":2.3260421917E10,"percent_change_24h":-0.19,"price":227.32432918,"volume_24h":1.49265685549155E9,"percent_change_7d":7.69}}}}

我想像这样退货:

return new ResponseEntity<JSONObject>(coinmarketcapJSONObject, HttpStatus.OK);

但是,当我这样做时,我总是遇到错误:

  

“未找到类型为class的返回值的转换器   org.json.JSONArray”

enter image description here

我在网上看到必须安装Jackson依赖项。我安装了它们,但没有任何改变。

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.7</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.7</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.7</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-json-provider</artifactId>
    <version>2.9.7</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-jaxb-annotations</artifactId>
    <version>2.9.7</version>
</dependency>

1 个答案:

答案 0 :(得分:2)

您可以将其作为String返回。

return new ResponseEntity<String>(coinmarketcapJSONObject.toString(), HttpStatus.OK);