简体   繁体   中英

How to convert an attribute ArrayList<String> or ArrayList<Integer> or ArrayList<MYCLASS> from a JSON object to a java object?

I'm pretty new at programming. And i'm trying to save my objects into a txt with JSON. But I have a problem when I try to pass the JSON object to my constructor.

I have this class.

public class Aluno {
protected String matricula;
protected ArrayList<Integer> concluidas;
protected ArrayList<Integer> cursando;
protected ArrayList<Notas> notas;

And I use this method to convert it to JSON

public JSONObject toJson(){
JSONObject json = new JSONObject();
json.put("matricula",this.matricula);
json.put("concluidas",this.concluidas);
json.put("notas",this.notas);
return json; }

The problem is at my constructor:

public Aluno(JSONObject json) {
    this.matricula = json.getString("matricula");
    this.concluidas = (ArrayList<Integer>) json.get("concluidas");

    this.notas = (ArrayList<Notas>) json.get("notas");


    this.cursando = (ArrayList<Integer>) json.get("cursando");
}

I get errors here

this.concluidas = (ArrayList<Integer>) json.get("concluidas");

ERROR : Exception in thread "main" java.lang.ClassCastException: json.JSONArray cannot be cast to java.util.ArrayList

The same for ArrayList cursando and ArrayList notas.

ArrayList<Integer> concluidas = new ArrayList<Integer>();     
JSONArray jArray = (JSONArray)json.get("concluidas");; 
if (jArray != null) { 
   for (int i=0;i<jArray.length();i++){ 
    listdata.add(jArray.getInt(i));
   } 
} 

Similarly you can convert other JSONArrays too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM