简体   繁体   English

线程“main”中的异常 java.lang.ClassCastException:class org.json.simple.JSONObject 无法转换为 class java.util.List

[英]Exception in thread "main" java.lang.ClassCastException: class org.json.simple.JSONObject cannot be cast to class java.util.List

I want to read a json file and store it into objects so that I can use it in my logic.我想读取一个 json 文件并将其存储到对象中,以便我可以在我的逻辑中使用它。 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.经过多次尝试,我能够将 json 提取到 Map 中。但我希望将值存储在 object 中,而不是 map 中。

Below is my code where I tried to fetch it and store in Currency object.下面是我尝试获取它并以货币 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下面是我的 JSON 文件

{
    "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:下面是我创建的用于存储 JSON 值的 POJO 类:

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货币.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贸易.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.我还尝试了 GSON 方法,但无法以所需格式获取它。

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.任何帮助,将不胜感激。

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.正如 Abrar Ansari 所说,将变量的类型从 ArrayList 更改为 Trade class 中的 String。同时将 CurrencyMarket class 中的货币和贸易变量重命名为货币和交易。 Make all fields private in all model classes and make sure you have default constructors in all model classes.在所有 model 类中将所有字段设为私有,并确保在所有 model 类中都有默认构造函数。 Then use Jackson's ObjectMapper to deserialize the json file into an object of type CurrentMarket:然后使用 Jackson 的 ObjectMapper 将 json 文件反序列化为 CurrentMarket 类型的 object:

ObjectMapper objectMapper = new ObjectMapper();
CurrentMarket currentMarket = objectMapper.readValue(new ClassPathResource("AvailableMarket.json").getFile(),
        CurrentMarket.class);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 线程“main”java.lang.ClassCastException 中的异常:类 java.util.LinkedHashMap 无法转换为类 java.util.List - Exception in thread "main" java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class java.util.List 线程“主”java.lang.ClassCastException 中的异常:www.logisense.com.pogos.wizardNewProduct.ProductWorkingDates 不能转换为 Z93F725A07423FEList21C846D48。 - Exception in thread "main" java.lang.ClassCastException: www.logisense.com.pogos.wizardNewProduct.ProductWorkingDates cannot be cast to java.util.List java.lang.ClassCastException: myClass 不能转换为 class java.util.List - java.lang.ClassCastException: myClass cannot be cast to class java.util.List java.lang.ClassCastException: 使用 java 读取 json 文件时,无法将 org.json.simple.JSONArray 转换为 org.json.simple.JSONObject 错误 - java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject error when reading json file iwith java 为什么我在线程“主”java.lang.ClassCastException:ArrayList 不能使用此代码强制转换为 java.util.List 中不断出现异常? [等候接听] - Why do i keep getting Exception in thread “main” java.lang.ClassCastException: ArrayList cannot be cast to java.util.List with this code? [on hold] 线程“ main”中的异常java.lang.ClassCastException:java.util.HashMap无法转换为org.openqa.selenium.WebElement - Exception in thread “main” java.lang.ClassCastException: java.util.HashMap cannot be cast to org.openqa.selenium.WebElement 线程“主”中的异常java.lang.ClassCastException:无法将java.util.ArrayList强制转换为org.openqa.selenium.WebElement - Exception in thread “main” java.lang.ClassCastException: java.util.ArrayList cannot be cast to org.openqa.selenium.WebElement java.lang.ClassCastException:org.hibernate.internal.SQLQueryImpl无法转换为java.util.List如何修复 - java.lang.ClassCastException: org.hibernate.internal.SQLQueryImpl cannot be cast to java.util.List how to fix java.lang.ClassCastException:java.lang.String[] 不能转换为 java.util.List - java.lang.ClassCastException: java.lang.String[] cannot be cast to java.util.List 线程“主”java.lang.ClassCastException 中的异常:java.util.LinkedHashMap 无法转换为自定义 Object - Exception in thread “main” java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to Custom Object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM