简体   繁体   中英

How to return a JSONObject instead HashMap with ResponseEntity? (No converter found for return value of type: class org.json.JSONObject)

I am able to return an HashMap as a JSON from my REST API built on Spring Boot. Here my Method:

@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);
}

Here is what is printed in the terminal:

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}

I want to return my JSONObject "coinmarketcapsnapshotsJSONObject" instead "coinmarketcapsnapshotsHashMap", but when I do it, I keep getting stuck with this error:

No converter found for return value of type: class org.json.JSONObject

As suggested in some posts found on web, I added Jackson as new dependency in pom.xml file:

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

Unfortunately this didn't change anything.

Do you have any suggestion to improve the process of building a JSON for a REST API on Spring Boot?

When I return the HashMap, the output looks like that:

在此处输入图片说明

在此处输入图片说明

@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); 
}   

Now you're returning a json object that contains the value of "data" key @118218

HttpStatus.OK is the default return value for Http endpoints using Spring and therefore specifying it is unnecessary, thereby rendering the entire ResponseEntity unnecessary:

@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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM