如何处理 "cannot be cast to class" 错误 - GSON JAVA

How to deal with "cannot be cast to class" error - GSON JAVA

我正在尝试将我的列表写入抽象模型中的 jtable,然后它的 return 给我这个错误。在我看来,这可能是由列表格式引起的?名字和金额放错地方了。这是我的完整错误信息: 线程 "AWT-EventQueue-0" java.lang.ClassCastException 中的异常:class com.google.gson.internal.LinkedTreeMap 无法转换为 class Model.Medicine(com.google.gson.internal.LinkedTreeMap 和 Model.Medicine在加载器的未命名模块中 'app')

有一个代码: 这是我的药class

public class Medicine {

private String name;
private String amount;

public Medicine( String amount, String name){
    this.name = name;
    this.amount = amount;
}

public String getName() {return name;}
public void setName(String name){this.name = name;}

public String getAmount(){return amount;}
public void setAmount(String amount){this.amount = amount;}
}

这是我的转换代码:

public List<Medicine> FromJsonToArray() throws IOException {
    String medicineJson = initArray("Medicines.json").toString();
    Gson gson = new Gson();
    List<Medicine> medicineArray = gson.fromJson(medicineJson, List.class);
    return medicineArray;
    }

转换后我的列表如下所示:

[{amount=123,name=Ibuprofen},{amount=333,name=Ketonal},...]

我的json:

[
{
    "amount": "123",
    "name": "Ibuprofen"
},
{
    "amount": "333",
    "name": "Ketonal"
}
]

最后 table 模型 class 错误:

public class MedicineTableModel extends AbstractTableModel {
private List<Medicine> medicines;
private String[] columns;

public  MedicineTableModel(List<Medicine> aMedicineList){
    super();
    medicines = aMedicineList;
    columns = new String[]{"Name", "Amount"};
}


@Override
public int getRowCount() {
    return medicines.size();
}

@Override
public int getColumnCount() {

    return columns.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
    if (columnIndex<medicines.size())
    {
        Medicine c= medicines.get(rowIndex); <---- there is a problem :O
        if(rowIndex == 0) {

            return(c.getName());
        }
     }
    return null;
}
public String getColumnName(int col) {
    return columns[col] ;
}
}
public List<Medicine> FromJsonToArray() throws IOException {
    String medicineJson = initArray("Medicines.json").toString();
    Gson gson = new Gson();
    Type medicineListType = new TypeToken<List<Medicine>>() {}.getType();
    List<Medicine> medicineArray = gson.fromJson(medicineJson, medicineListType);
    return medicineArray;
}

应该可以解决问题。

基本上,告诉 gson 反序列化到特定 class.

列表是一种变通方法

这是必需的,因为泛型在运行时丢失并且您的 json 被反序列化为 List<LinkedTreeMap> 而不是 List<Medicine>