0

I have a class that implements Serializable...

public class Hop implements Serializable {
    private static final long serialVersionUID = 1L;

    public double d1;           
    public double d2;
    public Date date1;      
    public String string;   
    public Date date2;      
}

What I have is an List of Hops ...

List<Hop> hops = new ArrayList<Hop>();
hops.add(hop1);
hops.add(hop2);

JSONObject json = new JSONObject();
json.put("uniqueArrays", new JSONArray(hops));
String arrayList = json.toString();

then I saved this String in SQLite with many other things ...

When I retrieve this String from DB, I want to convert it to List but I am not succesfull ...

How I to it:

JSONObject json = new JSONObject(arrayList );
JSONArray items = json.optJSONArray("uniqueArrays");

how can I convert JSONArray to List ?

//EDIT This is how they looks like when I retrieve them from DB:

 JSONObject: {"uniqueArrays":["com.myapp.app.Hop@41c18ce8"]}
 JSONArray :["com.myapp.app.Hop@41c18ce8"]
Matej Špilár
  • 2,617
  • 3
  • 15
  • 28

1 Answers1

1

To get list of objects from jsonArray,first get JSONObject from jsonArray then get class object from that JSONobject. So use below code:

JSONArray items = json.optJSONArray("uniqueArrays");
List<Hop> hopsData = new ArrayList<Hop>();

for (int i=0;i<items.length();i++){ 
    JSONObject jObj = items.getJSONObject(i);
    Hop  objHop = new Hop();
    objHop.d1 =jObj.getDouble("d1");
    objHop.d2 =jObj.getDouble("d2");
    objHop.date1 =Date.parse(jObj.getString("date1"));
    objHop.string =jObj.getString("string");
    objHop.date2 = Date.parse(jObj.getString("date2"));
    hopsData.add(objHop);
} 

Edit

Your conversion from Arraylist to jsonarray is wrong.So convert arraylist to jsonarray in this way.

List<Hop> hops = new ArrayList<Hop>();
hops.add(hop1); 
hops.add(hop2);
JSONArray jsonArray = new JSONArray();

for(Hop objHop : hops){
       JSONObject jsonObject= new JSONObject();
       jsonObject.put("d1", objHop.d1);
       jsonObject.put("d2", objHop.d2);
       jsonObject.put("date1", String.valueOf(objHop.date1));
       jsonObject.put("string", objHop.string);
       jsonObject.put("date2", String.valueOf(objHop.date2));
       jsonArray.put(jsonObject);
   }
Giru Bhai
  • 14,370
  • 5
  • 46
  • 74