How to convert json to ArrayList object in Java?
10,231
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.
Author by
Danilo
Updated on June 25, 2022Comments
-
Danilo almost 2 years
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