簡體   English   中英

在內部存儲對象的 JSONArray 並稍后讀取它們 ANDROID

[英]Store JSONArray of objects internally and read them later ANDROID

我正在嘗試在 android 應用程序中創建和存儲一個 JSONArray 對象(在這種情況下是產品),然后在用戶關閉應用程序時讀取它們。

到目前為止,我有這個:

JSONArray jsArray = new JSONArray();
for(int i = 0; i<productList.size(); i++){
    jsArray.put(productList.get(i));
}
FileOutputStream fos = this.openFileOutput(filename,Context.MODE_PRIVATE);

String jsonString = jsArray.toString();
fos.write(jsonString.getBytes());
fos.close();

productList是一個產品對象數組。

然后當使用關閉並打開應用程序時,這是我要閱讀的代碼:

FileInputStream fis = this.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();

JSONObject jsonobject = new JSONObject();

String jsongString = readFromFile();
JSONArray jarray = new JSONArray(jsongString);
System.out.println("AQUI");
System.out.println(jarray.get(0));

這不起作用,我嘗試獲取存儲在jarray並返回:

com.example.frpi.listacompra.Producto@b120c68

有誰知道發生了什么?

編輯:文件名是“products.json”

在這部分代碼中:

jsArray.put(productList.get(i));

您嘗試將一個對象放入您的JSONArray 中,因此,您遇到了這個問題。 為了解決這個問題,您必須將您的對象轉換為JSONObject ,然后嘗試將其放入您的JSONArray 中 例如,如果您的 Product 類如下所示:

public class Product {
    private Integer id;
    private String name;

    public Product(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

你必須像這樣改變你的代碼:

JSONArray jsArray = new JSONArray();
for( int i =0; i<productList.size(); i++){
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("id", productList.get(i).getId());
    jsonObject.put("name", productList.get(i).getName());
    jsArray.put(jsonObject);
}

暫無
暫無

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

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