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

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.