简体   繁体   中英

How to parse this JSON response in Android?

I have tried to parse the data still unable to do .

String jsonData = "[{\"id\":\"7\",\"customer_id\":\"1\",\"product_type_id\":\"1\",\"quantity\":\"1\",\"ordered_on\":\"2015-12-01\",\"product_consumption_type\":\"general\",\"reason\":\"\",\"productType\":{\"id\":\"1\",\"name\":\"Full Cream Milk\",\"description\":\"\",\"measurement\":\"\"}},{\"id\":\"3\",\"customer_id\":\"1\",\"product_type_id\":\"1\",\"quantity\":\"0\",\"ordered_on\":\"2015-12-02\",\"product_consumption_type\":\"general\",\"reason\":\"\",\"productType\":{\"id\":\"1\",\"name\":\"Full Cream Milk\",\"description\":\"\",\"measurement\":\"\"}}]";

This is what I've tried so far:

try {
    JsonArrayRequest req = new JsonArrayRequest(jsonData, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            Log.d(TAG, response.toString());
            try {
                //parsing the value of jsaon array
                for (int i = 0; i < response.length(); i++) {
                    JSONObject details = (JSONObject) response.get(i);
                    String da = details.getString("ordered_on");
                    int qty = Integer.parseInt(details.getString("quantity"));
                    JSONObject prod_det = details.getJSONObject("productType");
                    String na = prod_det.getString("name");
                    ProductType pt = new ProductType(na, qty);
                    Product prod = new Product(da, pt);
                    list.add(prod);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(MonthlySummaryActivity.this, "ERROR" + e.getMessage(), Toast.LENGTH_SHORT).show();
                adapter.notifyDataSetChanged();
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(MonthlySummaryActivity.this, "error::" + error.getMessage(), Toast.LENGTH_LONG).show();

        }
    });
} catch (Exception ex) {
    ex.printStackTrace();
}
loading.hide();
return list;

you can parse JSON data in two ways.

1) Create your own parser class.

2) Use library for parsing json string.

1) if json string is short then you should go with your own parser class as below.

String name;

        try {
            JSONArray array = new JSONArray(YOUR JSON STRING);
            JSONObject obj;
            for (int i = 0; i < array.length(); i++) {
                obj = array.getJSONObject(i);
                name = obj.getString(KEY_NAME);
                ......
            }

        }catch (Exception e){
            e.printStackTrace();
        }

2) use Gson library. for Gson u can use this .

Hope I could help u.

public List<Product> parse(String jsonData) throws JSONException {
    List<Product> productList = new ArrayList();
    JSONArray orderArray = new JSONArray(jsonData);
    for (int i = 0, count = orderArray.length(); i < count; i++) {
        JSONObject productJO = orderArray.getJSONObject(i);

        ProductType productType = new ProductType();
        // parse the product type
        JSONObject productTypeJO = productJO.getJSONObject("productType");
        String typeId = productTypeJO.getString("id");
        String name = productTypeJO.getString("name");
        String description = productTypeJO.getString("description");
        String measurement = productTypeJO.getString("measurement");

        productType.setId(typeId);
        productType.setName(name);
        productType.setDescription(description);
        productType.setMeasurement(measurement);

        // parse the product
        String id = productJO.getString("id");
        String customerId = productJO.getString("customer_id");
        String productTypeId = productJO.getString("product_type_id");
        String quantity = productJO.getString("quantity");
        String orderedOn = productJO.getString("ordered_on");
        String productConsumptionType = productJO.getString("product_consumption_type");
        String reason = productJO.getString("reason");

        Product product = new Product();
        product.setId(id);
        product.setCustomerId(customerId);
        product.setProductTypeId(productTypeId);
        product.setQuantity(quantity);
        product.setOrderedOn(orderedOn);
        product.setProductConsumptionType(productConsumptionType);
        product.setReason(reason);
        product.setProductType(productType);

        productList.add(product);
    }
    return productList;
}

Simple and Efficient : Use Googlle's Gson library

  • Put this in build.gradle file : implementation 'com.google.code.gson:gson:2.6.2'
  • Now convert the JSON String to a convenient datastrucutre like HashMap in 2 lines like this.

Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(JsonString , type);

Thank me later :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM