How to deal with “cannot be cast to class” error – GSON JAVA

Tags: , , ,



i am trying to write my list to jtable in abstract model and then its return to me this error. In my opinion it could be cause by list format? name and amount are in wrong place. This is my full error message: Exception in thread “AWT-EventQueue-0” java.lang.ClassCastException: class com.google.gson.internal.LinkedTreeMap cannot be cast to class Model.Medicine (com.google.gson.internal.LinkedTreeMap and Model.Medicine are in unnamed module of loader ‘app’)

There is a code: This is mine Medicine 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;}
}

This is my converting code:

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

After convert my List looks like:

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

My json:

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

And finally table model class with error:

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] ;
}
}

Answer

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

should do the trick.

Basically it is a workaround to tell gson to deserialize to a list of particular class.

That is required because generics are lost at runtime and your json was being deserialized to List<LinkedTreeMap> instead of List<Medicine>.



Source: stackoverflow