Home > Back-end >  Cannot convert nested JSON to POJO using Resttemplate in Spring Boot
Cannot convert nested JSON to POJO using Resttemplate in Spring Boot

Time:07-07

I have the following JSON, from which I want to store specific fields in database.

JSON OBJECT

{
    "data": [
        {
            "screen_ID": "23",
            "screen_data": {
                "ob": "Yes",
                "next_page": 2,
                "news": [
                    {
                        "news_ID": 2844573,
                        "hash": "ef52eadab9d2bdf69b6a288e6de7797b",
                        "providerId": "73",
                        "itemCategoryTags": "301",
                        "news_provider_name": "CoinQuora",
                        "last_updated": "2022-07-06 16:00:38",
                        "last_updated_uts": 1657123238,
                        "type": "text",
                        "HEADLINE": "BTC, ETH, SHIB, STEPN, PancakeSwap: Top 5 Trending Coins",
                        "BODY": "",
                        "news_link": "https://www.investing.com/news/cryptocurrency-news/btc-eth-shib-stepn-pancakeswap-top-5-trending-coins-2844573",
                        "third_party_url": "",
                        "related_image": "https://i-invdn-com.investing.com/news/LYNXNPEE340J6_S.jpg",
                        "related_image_big": "https://i-invdn-com.investing.com/news/LYNXNPEE340J6_L.jpg",
                        "vid_filename": "",
                        "comments_cnt": "0",
                        "is_partial": "yes",
                        "itemType": "hosted",
                        "news_type": "AkapiAdmin"
                    },
                    {
                        "news_ID": 2844563,
                        "hash": "f671179bec5cc29409c00f89b9494b3f",
                        "providerId": "72",
                        "itemCategoryTags": "301",
                        "news_provider_name": "BTC Peers",
                        "last_updated": "2022-07-06 15:30:44",
                        "last_updated_uts": 1657121444,
                        "type": "text",
                        "HEADLINE": "Buy the Bitcoin dip, Wolf of Wall Street Jordan Belfort advises",
                        "BODY": "",
                        "news_link": "https://www.investing.com/news/cryptocurrency-news/buy-the-bitcoin-dip-wolf-of-wall-street-jordan-belfort-advises-2844563",
                        "third_party_url": "",
                        "related_image": "https://i-invdn-com.investing.com/news/LYNXNPEF310CO_S.jpg",
                        "related_image_big": "https://i-invdn-com.investing.com/news/LYNXNPEF310CO_L.jpg",
                        "vid_filename": "",
                        "comments_cnt": "0",
                        "is_partial": "yes",
                        "itemType": "hosted",
                        "news_type": "AkapiAdmin"
                    },
                    {
                        "news_ID": 2844549,
                        "hash": "b26f2704330df75e5df3a407f229b984",
                        "providerId": "43",
                        "itemCategoryTags": "301",
                        "news_provider_name": "Cointelegraph",
                        "last_updated": "2022-07-06 15:00:17",
                        "last_updated_uts": 1657119617,
                        "type": "text",
                        "HEADLINE": "Bear market delivery! Bitcoiner rejoins DoorDash to buy more BTC",
                        "BODY": "<p>What did you do in the 2022 bear market, anon? For one Bitcoiner, the opportunity to take on a second job to &ldquo;stack sats&rdquo; (buy more <span pair_ID=\"1057391\">Bitcoin</span> (BTC)), was too great. Isaiah, the founder of the Cleveland Bitcoin Meetup, is delivering food to Ohio residents to earn cash on the side.</p>\n<p>Isaiah told Cointelegraph &ldquo;I joined DoorDash 2 years ago. But I only recently started doing it again once the price fell into the 20[K]s.&rdquo; DoorDash is an American food delivery service (similar to Glovo or Deliveroo), where riders pick up food from restaurants to take to people&rsquo;s homes. </p>\nThe Bitcoin price is under the 200wSMA (blue line) and has been since the 13th June. Source: Trading View <p><a href=\"https://cointelegraph.com/news/bear-market-delivery-ohio-guy-rejoins-doordash-to-buy-more-bitcoin\" target=\"_blank\" rel=\"nofollow\">Continue Reading on Coin Telegraph</a></p><span id=\"197.47.52.213\"> </span>",
                        "news_link": "https://www.investing.com/news/cryptocurrency-news/bear-market-delivery-bitcoiner-rejoins-doordash-to-buy-more-btc-2844549",
                        "third_party_url": "",
                        "related_image": "https://i-invdn-com.investing.com/news/external-images-thumbnails/pic1163faf2492507c0bd6e81e75d3f560d.jpg",
                        "related_image_big": "https://d1-invdn-com.investing.com/content/pic1163faf2492507c0bd6e81e75d3f560d.jpg",
                        "vid_filename": "",
                        "comments_cnt": "0",
                        "is_partial": "no",
                        "itemType": "hosted",
                        "news_type": "AkapiAdmin"
                    },
                    {
                        "news_ID": 2844474,
                        "hash": "e06dd2d44992b97b254e611c8318a269",
                        "providerId": "43",
                        "itemCategoryTags": "301",
                        "news_provider_name": "Cointelegraph",
                        "last_updated": "2022-07-06 12:40:27",
                        "last_updated_uts": 1657111227,
                        "type": "text",
                        "HEADLINE": "ARK Invest 'neutral to positive' on Bitcoin price as analysts await capitulation",
                        "BODY": "<p><span pair_ID=\"1057391\">Bitcoin</span> (BTC) has a &ldquo;neutral to positive&rdquo; outlook despite staying below $20,000, according to ARK Investment Management.</p>\n<p>In its latest \"Bitcoin Monthly\" report, the American asset management giant flagged signs that BTC price action is close to bottoming.</p>\n<span pair_ID=\"945629\">BTC/USD</span> 1-week candle chart (Bitstamp) with 200MA. Source: TradingView<p><a href=\"https://cointelegraph.com/news/ark-invest-neutral-to-positive-on-bitcoin-price-as-analysts-await-capitulation\" target=\"_blank\" rel=\"nofollow\">Continue Reading on Coin Telegraph</a></p><span id=\"197.47.52.213\"> </span>",
                        "news_link": "https://www.investing.com/news/cryptocurrency-news/ark-invest-neutral-to-positive-on-bitcoin-price-as-analysts-await-capitulation-2844474",
                        "third_party_url": "",
                        "related_image": "https://i-invdn-com.investing.com/news/external-images-thumbnails/pice4e7123a9cf8375e9fc405a2fb0c8ecd.jpg",
                        "related_image_big": "https://d1-invdn-com.investing.com/content/pice4e7123a9cf8375e9fc405a2fb0c8ecd.jpg",
                        "vid_filename": "",
                        "comments_cnt": "0",
                        "is_partial": "no",
                        "itemType": "hosted",
                        "news_type": "AkapiAdmin"
                    },
                    {
                        "news_ID": 2844468,
                        "hash": "e0c53a38449381fc3d72bf64181274c5",
                        "providerId": "73",
                        "itemCategoryTags": "301",
                        "news_provider_name": "CoinQuora",
                        "last_updated": "2022-07-06 12:30:40",
                        "last_updated_uts": 1657110640,
                        "type": "text",
                        "HEADLINE": "LTC, BUSD, CRV, CVX, and SRM See Increase in Accumulation",
                        "BODY": "",
                        "news_link": "https://www.investing.com/news/cryptocurrency-news/ltc-busd-crv-cvx-and-srm-see-increase-in-accumulation-2844468",
                        "third_party_url": "",
                        "related_image": "https://i-invdn-com.investing.com/news/litecoin_150x108_S_1556445302.jpg",
                        "related_image_big": "https://i-invdn-com.investing.com/news/litecoin_800x533_L_1556445302.jpg",
                        "vid_filename": "",
                        "comments_cnt": "0",
                        "is_partial": "yes",
                        "itemType": "hosted",
                        "news_type": "AkapiAdmin"
                    },
                    {
                        "news_ID": 2844459,
                        "hash": "e975f0d4040cb9595c88e17a33003e95",
                        "providerId": "73",
                        "itemCategoryTags": "301",
                        "news_provider_name": "CoinQuora",
                        "last_updated": "2022-07-06 12:00:35",
                        "last_updated_uts": 1657108835,
                        "type": "text",
                        "HEADLINE": "Minima Blockchain Now Boasts More Nodes Than Bitcoin",
                        "BODY": "",
                        "news_link": "https://www.investing.com/news/cryptocurrency-news/minima-blockchain-now-boasts-more-nodes-than-bitcoin-2844459",
                        "third_party_url": "",
                        "related_image": "https://i-invdn-com.investing.com/news/moved_small-LYNXMPEI5D0A7_L.jpg",
                        "related_image_big": "https://i-invdn-com.investing.com/news/moved_LYNXMPEI5D0A7_L.jpg",
                        "vid_filename": "",
                        "comments_cnt": "0",
                        "is_partial": "yes",
                        "itemType": "hosted",
                        "news_type": "AkapiAdmin"
                    },
                    {
                        "news_ID": 2844439,
                        "hash": "7dfaa6cec055138ece1c47913a7edfc7",
                        "providerId": "74",
                        "itemCategoryTags": "301",
                        "news_provider_name": "DailyCoin",
                        "last_updated": "2022-07-06 11:30:56",
                        "last_updated_uts": 1657107056,
                        "type": "text",
                        "HEADLINE": "Crack the Vauld: Nexo Offers to Buy Out Struggling Crypto Platform",
                        "BODY": "",
                        "news_link": "https://www.investing.com/news/cryptocurrency-news/crack-the-vauld-nexo-offers-to-buy-out-struggling-crypto-platform-2844439",
                        "third_party_url": "",
                        "related_image": "https://i-invdn-com.investing.com/news/external-images-thumbnails/pice56068e25358524c8ab8218d4faef6c6.jpg",
                        "related_image_big": "https://d1-invdn-com.investing.com/content/pice56068e25358524c8ab8218d4faef6c6.jpg",
                        "vid_filename": "",
                        "comments_cnt": "0",
                        "is_partial": "yes",
                        "itemType": "hosted",
                        "news_type": "AkapiAdmin"
                    },
                    {
                        "news_ID": 2844438,
                        "hash": "3a024868641cbf70cbb60cf3d0ee8807",
                        "providerId": "73",
                        "itemCategoryTags": "301",
                        "news_provider_name": "CoinQuora",
                        "last_updated": "2022-07-06 11:30:37",
                        "last_updated_uts": 1657107037,
                        "type": "text",
                        "HEADLINE": "Celsius Liquidation Drops to $2,722 in Light of New Loan Repayment",
                        "BODY": "",
                        "news_link": "https://www.investing.com/news/cryptocurrency-news/celsius-liquidation-drops-to-2722-in-light-of-new-loan-repayment-2844438",
                        "third_party_url": "",
                        "related_image": "https://i-invdn-com.investing.com/news/cedb56c793cebdd4180320ed33651e41_S.jpg",
                        "related_image_big": "https://i-invdn-com.investing.com/news/cedb56c793cebdd4180320ed33651e41_L.jpg",
                        "vid_filename": "",
                        "comments_cnt": "0",
                        "is_partial": "yes",
                        "itemType": "hosted",
                        "news_type": "AkapiAdmin"
                    },
                    {
                        "news_ID": 2844413,
                        "hash": "dffa7a57d7507932bb429e595d27456e",
                        "providerId": "10",
                        "itemCategoryTags": "14",
                        "news_provider_name": "Investing.com",
                        "last_updated": "2022-07-06 10:32:41",
                        "last_updated_uts": 1657103561,
                        "type": "text",
                        "HEADLINE": "Fed Minutes, Johnson Jeopardy, Amazon Grubhub Stake - What's Moving Markets",
                        "BODY": "",
                        "news_link": "https://www.investing.com/news/economy/fed-minutes-johnson-jeopardy-amazon-grubhub-stake--whats-moving-markets-2844413",
                        "third_party_url": "",
                        "related_image": "https://i-invdn-com.investing.com/news/moved_small-LYNXNPEI4H0KN_L.jpg",
                        "related_image_big": "https://i-invdn-com.investing.com/news/moved_LYNXNPEI4H0KN_L.jpg",
                        "vid_filename": "",
                        "comments_cnt": "6",
                        "is_partial": "yes",
                        "itemType": "written",
                        "news_type": "AkapiAdmin"
                    },
                    {
                        "news_ID": 2844397,
                        "hash": "020ec7f3bba3ac89fb20824ae3f75277",
                        "providerId": "74",
                        "itemCategoryTags": "301",
                        "news_provider_name": "DailyCoin",
                        "last_updated": "2022-07-06 10:00:46",
                        "last_updated_uts": 1657101646,
                        "type": "text",
                        "HEADLINE": "The Cases of Celsius, BlockFi, Voyager Shows Why Self-Sovereignty Should Be taken Seriously",
                        "BODY": "",
                        "news_link": "https://www.investing.com/news/cryptocurrency-news/the-cases-of-celsius-blockfi-voyager-shows-why-selfsovereignty-should-be-taken-seriously-2844397",
                        "third_party_url": "",
                        "related_image": "https://i-invdn-com.investing.com/news/external-images-thumbnails/picc58b680b3018230fcea8fea0504c1658.jpg",
                        "related_image_big": "https://d1-invdn-com.investing.com/content/picc58b680b3018230fcea8fea0504c1658.jpg",
                        "vid_filename": "",
                        "comments_cnt": "0",
                        "is_partial": "yes",
                        "itemType": "hosted",
                        "news_type": "AkapiAdmin"
                    }
                ]
            },
            "screen_layout": "[L2],[L2],[L2],[L2],[L2],{[L2],[L2],[L2],[L2],[P100],[L2],[L2],[L2],[L2],[L2]}*"
        }
    ]
}

I have created the following model class, to map the variables I want to store and next the following configuration class for business logic.

MODEL CLASS

package com.andrekreou.iot.bitpay.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.CreationTimestamp;

import javax.persistence.*;
import java.time.LocalDateTime;

//This class is responsible for mapping the key variables from
//the JSON array to be imported. The name keys from JSON have
//to be exactly the same as here, in order for data to be fetched.


//Don't forget to apply Lombok, at the end of the project as appendix!!!
@Entity
@Table
@JsonIgnoreProperties(ignoreUnknown = true)
public class BitPayRates {
    @Id
    @SequenceGenerator(
            name = "bitpay_sequence",
            sequenceName = "bitpay_sequence",
            allocationSize = 1
            )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "bitpay_sequence"
    )
    private Integer news_id;
    private String news_provider_name;
    private String HEADLINE;
    private String news_link;
    private String related_image;


    @CreationTimestamp
    private java.time.LocalDateTime timestamp;

    protected BitPayRates() {
    }

    public BitPayRates(Integer news_id,
                       String news_provider_name,
                       String HEADLINE,
                       String news_link,
                       String related_image,
                       LocalDateTime timestamp) {
        this.news_id = news_id;
        this.news_provider_name = news_provider_name;
        this.HEADLINE = HEADLINE;
        this.news_link = news_link;
        this.related_image = related_image;
        this.timestamp = timestamp;
    }

    public Integer getNews_id() {
        return news_id;
    }

    public void setNews_id(Integer news_id) {
        this.news_id = news_id;
    }

    public String getNews_provider_name() {
        return news_provider_name;
    }

    public void setNews_provider_name(String news_provider_name) {
        this.news_provider_name = news_provider_name;
    }

    public String getHEADLINE() {
        return HEADLINE;
    }

    public void setHEADLINE(String HEADLINE) {
        this.HEADLINE = HEADLINE;
    }

    public String getNews_link() {
        return news_link;
    }

    public void setNews_link(String news_link) {
        this.news_link = news_link;
    }

    public String getRelated_image() {
        return related_image;
    }

    public void setRelated_image(String related_image) {
        this.related_image = related_image;
    }

    public LocalDateTime getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(LocalDateTime timestamp) {
        this.timestamp = timestamp;
    }

    @Override
    public String toString() {
        return "BitPayRates{"  
                "news_id="   news_id  
                ", news_provider_name='"   news_provider_name   '\''  
                ", HEADLINE='"   HEADLINE   '\''  
                ", news_link='"   news_link   '\''  
                ", related_image='"   related_image   '\''  
                ", timestamp="   timestamp  
                '}';
    }
}

CONFIGURATION CLASS

package com.andrekreou.iot.bitpay.configuration;

import com.andrekreou.iot.bitpay.model.BitPayRates;
import com.andrekreou.iot.bitpay.repository.BitPayRatesRepo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;

//The configuration class to fetch data from url and execute the insertion
//of the data into the PostgreSQL database
@Configuration

public class BitPayRatesConfig {

    @Bean
    CommandLineRunner commandLineRunner(BitPayRatesRepo bitPayRatesRepo){
        return args -> {
            String url = "https://investing-cryptocurrency-markets.p.rapidapi.com/coins/get-news?pair_ID=1057391";
            RestTemplate restTemplate = new RestTemplate();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
            headers.set("X-RapidAPI-Key","605a619252msh709d3d6fa6fbdcdp155ef4jsn6cd36a1a4195");
            headers.set("X-RapidAPI-Host","investing-cryptocurrency-markets.p.rapidapi.com");

            HttpEntity<Object> request = new HttpEntity<>(headers);

            ResponseEntity<List<BitPayRates>> postEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    request,
                    new ParameterizedTypeReference<>() {
                    });

            List<BitPayRates> results = postEntity.getBody();
            bitPayRatesRepo.saveAll(results);
            System.out.println(results);
        };
    }
}

I am receiving the following error and I am little bit confused about what to do to solve it. Any advices???

STACK TRACE

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-07-06 20:48:38.171 ERROR 4160 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:774) ~[spring-boot-2.7.0.jar:2.7.0]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:755) ~[spring-boot-2.7.0.jar:2.7.0]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.7.0.jar:2.7.0]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.0.jar:2.7.0]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.0.jar:2.7.0]
    at com.andrekreou.iot.IotApplication.main(IotApplication.java:12) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.7.0.jar:2.7.0]
Caused by: org.springframework.web.client.RestClientException: Error while extracting response for type [java.util.List<com.andrekreou.iot.bitpay.model.BitPayRates>] and content type [application/json]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.ArrayList<com.andrekreou.iot.bitpay.model.BitPayRates>` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList<com.andrekreou.iot.bitpay.model.BitPayRates>` from Object value (token `JsonToken.START_OBJECT`)
 at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:120) ~[spring-web-5.3.20.jar:5.3.20]
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:1037) ~[spring-web-5.3.20.jar:5.3.20]
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:1020) ~[spring-web-5.3.20.jar:5.3.20]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:778) ~[spring-web-5.3.20.jar:5.3.20]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711) ~[spring-web-5.3.20.jar:5.3.20]
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:631) ~[spring-web-5.3.20.jar:5.3.20]
    at com.andrekreou.iot.bitpay.configuration.BitPayRatesConfig.lambda$commandLineRunner$0(BitPayRatesConfig.java:35) ~[classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:771) ~[spring-boot-2.7.0.jar:2.7.0]
    ... 10 common frames omitted
Caused by: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.ArrayList<com.andrekreou.iot.bitpay.model.BitPayRates>` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList<com.andrekreou.iot.bitpay.model.BitPayRates>` from Object value (token `JsonToken.START_OBJECT`)
 at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:391) ~[spring-web-5.3.20.jar:5.3.20]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:343) ~[spring-web-5.3.20.jar:5.3.20]
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:105) ~[spring-web-5.3.20.jar:5.3.20]
    ... 17 common frames omitted
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList<com.andrekreou.iot.bitpay.model.BitPayRates>` from Object value (token `JsonToken.START_OBJECT`)
 at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.13.3.jar:2.13.3]
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1741) ~[jackson-databind-2.13.3.jar:2.13.3]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1515) ~[jackson-databind-2.13.3.jar:2.13.3]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1462) ~[jackson-databind-2.13.3.jar:2.13.3]
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.handleNonArray(CollectionDeserializer.java:392) ~[jackson-databind-2.13.3.jar:2.13.3]
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:252) ~[jackson-databind-2.13.3.jar:2.13.3]
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:28) ~[jackson-databind-2.13.3.jar:2.13.3]
    at com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.readRootValue(DefaultDeserializationContext.java:323) ~[jackson-databind-2.13.3.jar:2.13.3]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4674) ~[jackson-databind-2.13.3.jar:2.13.3]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3682) ~[jackson-databind-2.13.3.jar:2.13.3]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:380) ~[spring-web-5.3.20.jar:5.3.20]
    ... 19 common frames omitted

2022-07-06 20:48:38.171  INFO 4160 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2022-07-06 20:48:38.186  INFO 4160 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2022-07-06 20:48:38.186  INFO 4160 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Process finished with exit code 0

CodePudding user response:

You need to create new model class which matches your response json. Model classes can be generated easily online. You can do it here. Copy paste these model classes in your project and use parent class in your response. Consider your parent class is Root. Then in your commandLineRunner after rest call, put below logic

Root response = postEntity.getBody();
//either manually map response to BitPayRates or use some mapping framework like https://mapstruct.org/
bitPayRatesRepo.saveAll(results);//save mapped result to database

CodePudding user response:

Problem is in this that you are trying to deserilize your response as array :

 ResponseEntity<List<BitPayRates>> postEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    request,
                    new ParameterizedTypeReference<>() {
                    });

But you are getting object as response (notice curly braces) :

{
    "data": []
    ...
}

Change above line to:

ResponseEntity<BitPayRates> postEntity = restTemplate.exchange(
                        url,
                        HttpMethod.GET,
                        request,
                        new ParameterizedTypeReference<>() {
                        });

And it should be fine.

  • Related