簡體   English   中英

如何轉換屬性ArrayList <String> 或ArrayList <Integer> 或ArrayList <MYCLASS> 從JSON對象到Java對象?

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

我是編程新手。 我正在嘗試使用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");

錯誤:線程“主”中的異常java.lang.ClassCastException:json.JSONArray無法轉換為java.util.ArrayList

ArrayList cursando和ArrayList注意相同。

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

同樣,您也可以轉換其他JSONArrays。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM