首页 > 解决方案 > 在内部存储对象的 JSONArray 并稍后读取它们 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”

标签: javaandroidarraysjson

解决方案


在这部分代码中:

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

推荐阅读