简体   繁体   中英

Store JSONArray of objects internally and read them later ANDROID

I am trying to create and store a JSONArray of objects ( in this case products) in an android app and later read them when the user closes the app.

So far I have this:

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 is an array of product objects.

Then when the uses closes and oppens the app this is my code to read:

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

This doesn't work, I tried getting what is stored in jarray and returns this:

com.example.frpi.listacompra.Producto@b120c68

Does anyone know what is happening?

EDIT: filename is "products.json"

In this part of code :

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

you try to put an object into your JSONArray , and because of that, you face this problem. For resolving this problem, you must convert your object into JSONObject and, after that, try to put it into your JSONArray . For example, if your Product class is like the following :

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

you must change your code like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM