0

I want to read a json file and store it into objects so that I can use it in my logic. After multiple attempts I was able to fetch the json into a Map. But I want the values to be stored in object and not a map.

Below is my code where I tried to fetch it and store in Currency object.

package com.springboot.currencyExchange;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import com.springboot.currencyExchange.model.*;
import com.springboot.currencyExchange.model.Currency;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.springboot.currencyExchange.service.MarketStrategyImpl;

@SpringBootApplication
public class CurrencyExchangeApplication {

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {
        // SpringApplication.run(CurrencyExchangeApplication.class, args);

        Object obj = new JSONParser().parse(new FileReader(
                "*absolute path*\AvailableMarket.json"));

        JSONObject jobj = (JSONObject) obj;
        JSONArray ja = (JSONArray) jobj.get("currencies");
        Iterator<Currency> itr1 = null;
        Iterator<CurrentMarket> itr2 = ja.iterator();
        while (itr2.hasNext()) {
            itr1 = (Iterator<Currency>) (((List) itr2.next()).iterator());
            while (itr1.hasNext()) {
                Currency pair = itr1.next();
            //  System.out.println(pair.getKey() + " : " + pair.getValue());

            }
        }

    }

}

Below is my JSON file

{
    "currencies": [
        {
            "currencyName": "Euro",
            "price": 80
        },
        {
            "currencyName": "Pound",
            "price": 90
        },
        {
            "currencyName": "USD",
            "price": 75
        }
    ],
    "trades": [
        {
            "take": "Euro",
            "give": "USD"
        },
        {
            "take": "USD",
            "give": "Pound"
        }
    ]
}

Below are the POJO classes I created to store the JSON values:

package com.springboot.currencyExchange.model;

import java.util.List;

public class CurrentMarket {

    public List<Currency> currency;
    public List<Trade> trade;

    public CurrentMarket() {
        super();
    }

    public List<Currency> getCurrency() {
        return currency;
    }

    public void setCurrency(List<Currency> currency) {
        this.currency = currency;
    }

    public List<Trade> getTrade() {
        return trade;
    }

    public CurrentMarket(List<Currency> currency, List<Trade> trade) {
        super();
        this.currency = currency;
        this.trade = trade;
    }

    @Override
    public String toString() {
        return "CurrentMarket [currency=" + currency + ", trade=" + trade + "]";
    }

    public void setTrade(List<Trade> trade) {
        this.trade = trade;
    }

}

Currency.java

package com.springboot.currencyExchange.model;

import java.io.Serializable;

@SuppressWarnings("serial")
public class Currency implements Serializable{
    String currencyName;
    Double price;

    public String getCurrencyName() {
        return currencyName;
    }

    public void setCurrencyName(String currencyName) {
        this.currencyName = currencyName;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Currency [currencyName=" + currencyName + ", price=" + price + "]";
    }

    public Currency(String currencyName, Double price) {
        super();
        this.currencyName = currencyName;
        this.price = price;
    }
}

Trade.java

package com.springboot.currencyExchange.model;

import java.util.ArrayList;

public class Trade {
    ArrayList<String> take;
    ArrayList<String> give;

    public ArrayList<String> getTake() {
        return take;
    }

    public Trade(ArrayList<String> take, ArrayList<String> give) {
        super();
        this.take = take;
        this.give = give;
    }

    public void setTake(ArrayList<String> take) {
        this.take = take;
    }

    public ArrayList<String> getGive() {
        return give;
    }

    public void setGive(ArrayList<String> give) {
        this.give = give;
    }

}

I also tried the GSON approach but couldn't fetch it in desired format.

Below is the error message I get with current setup:

Exception in thread "main" java.lang.ClassCastException: class org.json.simple.JSONObject cannot be cast to class java.util.List (org.json.simple.JSONObject is in unnamed module of loader 'app'; java.util.List is in module java.base of loader 'bootstrap')
    at com.springboot.currencyExchange.CurrencyExchangeApplication.main(CurrencyExchangeApplication.java:32)

I am not sure how else can I proceed. Any help would be appreciated.

SnailK
  • 1
  • 3
  • change your trade variables take and give to String from ArrayList – Abrar Ansari Mar 08 '22 at 13:12
  • Does this answer your question? [How to get the underlying String from a JsonParser (Jackson Json)](https://stackoverflow.com/questions/16825880/how-to-get-the-underlying-string-from-a-jsonparser-jackson-json) – pringi Mar 08 '22 at 13:14

1 Answers1

0

You need to make a few changes at first.

As Abrar Ansari said, change the type of the variables from ArrayList to String in the Trade class. Also rename the currency and trade variables from the CurrencyMarket class to currencies and trades. Make all fields private in all model classes and make sure you have default constructors in all model classes. Then use Jackson's ObjectMapper to deserialize the json file into an object of type CurrentMarket:

ObjectMapper objectMapper = new ObjectMapper();
CurrentMarket currentMarket = objectMapper.readValue(new ClassPathResource("AvailableMarket.json").getFile(),
        CurrentMarket.class);
Alex
  • 16
  • 3
  • Thanks Abrar Ansari and Alex, I did the suggested changes and it worked. I had to add annotate my model class Currency constructor with @ConstructorProperties({ "currencyName", "price" }) to avoid InvalidDefinitionException. – SnailK Mar 12 '22 at 15:33