4

i want convert json values to ArrayList objects in java...., i have:

{"Products":[
{
      "id":001,
      "name":"mouse"
    },
    {
      "id":002,
      "name":"Monitor"
    }
]}

// model

Public class Product {

   private int id; 
   private String name;

   //getters and setters
}

// and method

JSONArray jsonArray= new JSONArray(jsonProducts);
List<Product> list = new ArrayList<Product>();
Product p = new Product();

for(int i=0; i<jsonArray.length; i++) {
     product.setId(??);
     product.setName(??);
     list.add(??);
}

I'm using org.json

JJJ
  • 32,902
  • 20
  • 89
  • 102
Danilo
  • 91
  • 1
  • 1
  • 9
  • see this question : http://stackoverflow.com/questions/15158916/convert-json-array-to-a-java-list-object – M2E67 Apr 23 '17 at 05:28

1 Answers1

3

You need to use:

Product p = new Product(); 
p.setId( jsonArray.getJSONObject(i).getInt("id") );
p.setName( jsonArray.getJSONObject(i).getString("name") );
list.add(p)

All inside the loop, because you need to create a new product each time.