有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何将属性ArrayList<String>或ArrayList<Integer>或ArrayList<MYCLASS>从JSON对象转换为java对象?

我是编程新手。 我试图用JSON将我的对象保存到一个txt文件中。 但是当我试图将JSON对象传递给我的构造函数时,我遇到了一个问题

我有这门课

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

我使用这个方法将其转换为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; }

问题出在我的构造函数上:

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

我这里有错误

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

错误:线程“main”java中出现异常。lang.ClassCastException:json。JSONArray不能转换为java。util。ArrayList

ArrayList cursando和ArrayList notas也是如此


共 (1) 个答案

  1. # 1 楼答案

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

    同样,您也可以转换其他JSONArray