How to convert json to ArrayList object in Java?

Danilo picture Danilo · Apr 23, 2017 · Viewed 9.9k times · Source

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

Answer

Alejandro N&#250;&#241;ez picture Alejandro Núñez · Apr 23, 2017

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.