我能够从基于 Spring Boot 构建的 REST API 以 JSON 形式返回 HashMap。这是我的方法:@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"));我想返回我的 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/150
提交
取消