我能够从基于Spring Boot构建的REST API中将HashMap作为JSON返回。这是我的方法:
@ResponseBody
@Transactional
@GetMapping("create_coinmarketcap_snapshot")
public ResponseEntity<HashMap> create_coinmarketcap_snapshot() {
String jsonString = callURL("https://api.coinmarketcap.com/v2/ticker/?limit=5");
JSONArray coinmarketcapsnapshotsArray = new JSONArray();
JSONObject coinmarketcapsnapshotsJSONObject = new JSONObject();
HashMap<Integer, CoinmarketcapSnapshot> coinmarketcapsnapshotsHashMap = new HashMap<>();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject jsonObjectData = jsonObject.getJSONObject("data");
Iterator<?> keys = jsonObjectData.keys();
int count = 0;
while (keys.hasNext()) {
count++;
String key = (String) keys.next();
if (jsonObjectData.get(key) instanceof JSONObject) {
JSONObject jsonObjectDataCrypto = jsonObjectData.getJSONObject(key);
JSONObject jsonObjectDataCryptoQuotes = jsonObjectDataCrypto.getJSONObject("quotes").getJSONObject("USD");
CoinmarketcapSnapshot coinmarketcapsnapshotObject = new CoinmarketcapSnapshot();
String dateFormatted = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
coinmarketcapsnapshotObject.setTitle(jsonObjectDataCrypto.get("name") + " - " + dateFormatted);
coinmarketcapsnapshotObject.setCryptocurrencyId((int) jsonObjectDataCrypto.get("id"));
if(jsonObjectDataCrypto.get("rank")!=null){
coinmarketcapsnapshotObject.setRank((int) jsonObjectDataCrypto.get("rank"));
}
if(jsonObjectDataCrypto.get("circulating_supply")!=null){
coinmarketcapsnapshotObject.setCirculatingSupply((Double) jsonObjectDataCrypto.get("circulating_supply"));
}
if(jsonObjectDataCrypto.get("total_supply")!=null){
coinmarketcapsnapshotObject.setTotalSupply((Double) jsonObjectDataCrypto.get("total_supply"));
}
if(!jsonObjectDataCrypto.isNull("circulating_supply")) {
coinmarketcapsnapshotObject.setMaxSupply((Double) jsonObjectDataCrypto.get("circulating_supply"));
}
if(!jsonObjectDataCrypto.isNull("total_supply")) {
coinmarketcapsnapshotObject.setMaxSupply((Double) jsonObjectDataCrypto.get("total_supply"));
}
if(!jsonObjectDataCrypto.isNull("max_supply")) {
coinmarketcapsnapshotObject.setMaxSupply((Double) jsonObjectDataCrypto.get("max_supply"));
}
if(!jsonObjectDataCryptoQuotes.isNull("price")) {
coinmarketcapsnapshotObject.setPrice((Double) jsonObjectDataCryptoQuotes.get("price"));
}
if(!jsonObjectDataCryptoQuotes.isNull("volume_24h")) {
coinmarketcapsnapshotObject.setVolume24h((Double) jsonObjectDataCryptoQuotes.get("volume_24h"));
}
if(!jsonObjectDataCryptoQuotes.isNull("market_cap")) {
coinmarketcapsnapshotObject.setMarketCap((Double) jsonObjectDataCryptoQuotes.get("market_cap"));
}
if(!jsonObjectDataCryptoQuotes.isNull("percent_change_1h")) {
coinmarketcapsnapshotObject.setPercentChange1h((Double) jsonObjectDataCryptoQuotes.get("percent_change_1h"));
}
if(!jsonObjectDataCryptoQuotes.isNull("percent_change_24h")) {
coinmarketcapsnapshotObject.setPercentChange24h((Double) jsonObjectDataCryptoQuotes.get("percent_change_24h"));
}
if(!jsonObjectDataCryptoQuotes.isNull("percent_change_7d")) {
coinmarketcapsnapshotObject.setPercentChange7d((Double) jsonObjectDataCryptoQuotes.get("percent_change_7d"));
}
entityManager.persist(coinmarketcapsnapshotObject);
coinmarketcapsnapshotsArray.put(coinmarketcapsnapshotObject);
coinmarketcapsnapshotsJSONObject.put(String.valueOf(count),coinmarketcapsnapshotObject);
coinmarketcapsnapshotsHashMap.put(count, coinmarketcapsnapshotObject);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("\n\ncoinmarketcapsnapshotsArray:\n"+coinmarketcapsnapshotsArray);
System.out.println("\n\ncoinmarketcapsnapshotsJSONObject:\n"+coinmarketcapsnapshotsJSONObject);
System.out.println("\n\ncoinmarketcapsnapshotsHashMap:\n"+coinmarketcapsnapshotsHashMap);
return new ResponseEntity<>(coinmarketcapsnapshotsHashMap, HttpStatus.OK);
}
这是终端上打印的内容:
coinmarketcapsnapshotsArray:
["com.krown.entity.CoinmarketcapSnapshot@4d60f69f","com.krown.entity.CoinmarketcapSnapshot@4739c2f2","com.krown.entity.CoinmarketcapSnapshot@7d5bd573","com.krown.entity.CoinmarketcapSnapshot@43b5eb6d","com.krown.entity.CoinmarketcapSnapshot@26e1a633"]
coinmarketcapsnapshotsJSONObject:
{"1":"com.krown.entity.CoinmarketcapSnapshot@4d60f69f","2":"com.krown.entity.CoinmarketcapSnapshot@4739c2f2","3":"com.krown.entity.CoinmarketcapSnapshot@7d5bd573","4":"com.krown.entity.CoinmarketcapSnapshot@43b5eb6d","5":"com.krown.entity.CoinmarketcapSnapshot@26e1a633"}
coinmarketcapsnapshotsHashMap:
{1=com.krown.entity.CoinmarketcapSnapshot@4d60f69f, 2=com.krown.entity.CoinmarketcapSnapshot@4739c2f2, 3=com.krown.entity.CoinmarketcapSnapshot@7d5bd573, 4=com.krown.entity.CoinmarketcapSnapshot@43b5eb6d, 5=com.krown.entity.CoinmarketcapSnapshot@26e1a633}
我想返回我的JSONObject“ coinmarketcapsnapshotsJSONObject”而不是“ coinmarketcapsnapshotsHashMap”,但是当我这样做时,我一直陷于这个错误:
未找到类型为org.json.JSONObject的返回值的转换器
正如在网络上找到的一些帖子中所建议的那样,我在pom.xml文件中添加了Jackson作为新的依赖项:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
不幸的是,这没有任何改变。
您是否有任何建议可以改善在Spring Boot上为REST API构建JSON的过程?
当我返回HashMap时,输出如下所示:
答案 0 :(得分:0)
@GetMapping(produces={MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<?> create_coinmarketcap_snapshot() throws IOException {
UriComponentsBuilder builder =
UriComponentsBuilder.fromUriString("https://api.coinmarketcap.com/v2/ticker")
.queryParam("limit", "5");
ResponseEntity<String> response =
restTemplate.getForEntity(builder.toUriString(), String.class);
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(response.getBody());
JsonNode data = root.path("data");
data.forEach(jsonObject -> {
jsonObject.get("rank"); //extracting values from each json object
jsonObject.get("circulating_supply");
jsonObject.get("total_supply");
jsonObject.get("max_supply");
jsonObject.get("price");
jsonObject.get("volume_24h");
jsonObject.get("market_cap");
jsonObject.get("percent_change_1h");
jsonObject.get("percent_change_24h");
//... and so on
});
return ResponseEntity.ok(data);
}
现在,您将返回一个包含“ data”键@ 118218值的json对象
答案 1 :(得分:0)
HttpStatus.OK是使用Spring的Http端点的默认返回值,因此不需要指定它,从而使整个ResponseEntity变得不必要:
@ResponseBody
@Transactional
@GetMapping("create_coinmarketcap_snapshot")
public HashMap create_coinmarketcap_snapshot() {
String jsonString = callURL("https://api.coinmarketcap.com/v2/ticker/?limit=5");
JSONArray coinmarketcapsnapshotsArray = new JSONArray();
JSONObject coinmarketcapsnapshotsJSONObject = new JSONObject();
HashMap<Integer, CoinmarketcapSnapshot> coinmarketcapsnapshotsHashMap = new HashMap<>();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject jsonObjectData = jsonObject.getJSONObject("data");
Iterator<?> keys = jsonObjectData.keys();
int count = 0;
while (keys.hasNext()) {
count++;
String key = (String) keys.next();
if (jsonObjectData.get(key) instanceof JSONObject) {
JSONObject jsonObjectDataCrypto = jsonObjectData.getJSONObject(key);
JSONObject jsonObjectDataCryptoQuotes = jsonObjectDataCrypto.getJSONObject("quotes").getJSONObject("USD");
CoinmarketcapSnapshot coinmarketcapsnapshotObject = new CoinmarketcapSnapshot();
String dateFormatted = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
coinmarketcapsnapshotObject.setTitle(jsonObjectDataCrypto.get("name") + " - " + dateFormatted);
coinmarketcapsnapshotObject.setCryptocurrencyId((int) jsonObjectDataCrypto.get("id"));
if(jsonObjectDataCrypto.get("rank")!=null){
coinmarketcapsnapshotObject.setRank((int) jsonObjectDataCrypto.get("rank"));
}
if(jsonObjectDataCrypto.get("circulating_supply")!=null){
coinmarketcapsnapshotObject.setCirculatingSupply((Double) jsonObjectDataCrypto.get("circulating_supply"));
}
if(jsonObjectDataCrypto.get("total_supply")!=null){
coinmarketcapsnapshotObject.setTotalSupply((Double) jsonObjectDataCrypto.get("total_supply"));
}
if(!jsonObjectDataCrypto.isNull("circulating_supply")) {
coinmarketcapsnapshotObject.setMaxSupply((Double) jsonObjectDataCrypto.get("circulating_supply"));
}
if(!jsonObjectDataCrypto.isNull("total_supply")) {
coinmarketcapsnapshotObject.setMaxSupply((Double) jsonObjectDataCrypto.get("total_supply"));
}
if(!jsonObjectDataCrypto.isNull("max_supply")) {
coinmarketcapsnapshotObject.setMaxSupply((Double) jsonObjectDataCrypto.get("max_supply"));
}
if(!jsonObjectDataCryptoQuotes.isNull("price")) {
coinmarketcapsnapshotObject.setPrice((Double) jsonObjectDataCryptoQuotes.get("price"));
}
if(!jsonObjectDataCryptoQuotes.isNull("volume_24h")) {
coinmarketcapsnapshotObject.setVolume24h((Double) jsonObjectDataCryptoQuotes.get("volume_24h"));
}
if(!jsonObjectDataCryptoQuotes.isNull("market_cap")) {
coinmarketcapsnapshotObject.setMarketCap((Double) jsonObjectDataCryptoQuotes.get("market_cap"));
}
if(!jsonObjectDataCryptoQuotes.isNull("percent_change_1h")) {
coinmarketcapsnapshotObject.setPercentChange1h((Double) jsonObjectDataCryptoQuotes.get("percent_change_1h"));
}
if(!jsonObjectDataCryptoQuotes.isNull("percent_change_24h")) {
coinmarketcapsnapshotObject.setPercentChange24h((Double) jsonObjectDataCryptoQuotes.get("percent_change_24h"));
}
if(!jsonObjectDataCryptoQuotes.isNull("percent_change_7d")) {
coinmarketcapsnapshotObject.setPercentChange7d((Double) jsonObjectDataCryptoQuotes.get("percent_change_7d"));
}
entityManager.persist(coinmarketcapsnapshotObject);
coinmarketcapsnapshotsArray.put(coinmarketcapsnapshotObject);
coinmarketcapsnapshotsJSONObject.put(String.valueOf(count),coinmarketcapsnapshotObject);
coinmarketcapsnapshotsHashMap.put(count, coinmarketcapsnapshotObject);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("\n\ncoinmarketcapsnapshotsArray:\n"+coinmarketcapsnapshotsArray);
System.out.println("\n\ncoinmarketcapsnapshotsJSONObject:\n"+coinmarketcapsnapshotsJSONObject);
System.out.println("\n\ncoinmarketcapsnapshotsHashMap:\n"+coinmarketcapsnapshotsHashMap);
return coinmarketcapsnapshotsHashMap;
}