Skip to content

Instantly share code, notes, and snippets.

@cblunt
Created December 16, 2014 18:25
Show Gist options
  • Save cblunt/7865d8afc566287a9d4a to your computer and use it in GitHub Desktop.
Save cblunt/7865d8afc566287a9d4a to your computer and use it in GitHub Desktop.
Parsing list of objects in JSON
public class ProductsActivity extends Activity {
// ...
// onCreate(), etc.
// ...
/**
* Assuming a JSON feed similar to:
* {
* "products": [
* { id: 1001, name: "Guitar", price: 299.95 },
* { id: 1002, name: "Drums", price: 199.99 },
* { id: 1003, name: "Keyboard", price: 249.95 },
* .....
* ]
* }
*/
private List<Products> parse(JSONObject json) throws JSONException {
ArrayList<Product> records = new ArrayList<>();
JSONArray jsonProducts = json.getJSONArray("products");
for(int i =0; i < jsonImages.length(); i++) {
JSONObject jsonProduct = jsonImages.getJSONObject(i);
long id = jsonProduct.getLong("id");
String name = jsonImage.getString("title");
double price = jsonImage.getDouble("price");
Product product = new Product(id, name, price)
records.add(product)
}
return records;
}
private class Product {
private long mId;
private String mName;
private double mPrice;
public Product(long id, String name, double price) {
mId = id;
mName = name;
mPrice = price;
}
}
private class ProductsAdapter extends ArrayAdapter<Product> {
// ...
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.product_list_item, parent, false);
}
// NOTE: You would normally use the ViewHolder pattern here
TextView nameLabel = (TextView) convertView.findViewById(R.id.text1);
TextView priceLabel = (TextView) convertView.findViewById(R.id.text2);
Product prouct = getItem(position);
nameLabel.setText(product.getName());
priceLabel.setText(String.valueOf(product.getPrice()));
return convertView;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment