java - 在内部存储对象的 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”
解决方案
在这部分代码中:
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);
}
推荐阅读
- php - 如何在某个 HTML Dom 之后获取字符串
- python - 如何将 kde 的带宽交给 seaborn 的 distplot?
- javascript - 提交表单后,我的表单字段变为必填项?
- java - Java:for in for,相同的arraylist和比较
- ruby-on-rails - 如何为图像的回形针宝石验证添加 rspec
- php - PHP Mysqli 总是返回 0 行
- sql-server - 确定最终的 Windows 用户
- artifactory - jfrog rt glc 在 refs/remotes/* 中搜索匹配的工件存储库文件。git lfs 将这些文件放在 lfs\objects
- xslt - 尝试在结果文档中删除元素并重新排序元素
- javascript - 防止 VueX 中的持久状态锁定应用程序