Cody Blog

Software development

Parsing JSON string on Android

Given a json string, you could convert it to either JSONObject(str) or JSONArray(str). For example, This json response is from weather forecaset server:

http://api.openweathermap.org/data/2.5/forecast/daily?zip=545%2Ctw&mode=json&units=metric&cnt=7&appid=aa032e548c67daa9cd1bc64eec737960

The response json format is like this:

json

If you want to get the first max temperature value: 17.06:

    JSONObject weather = new JSONObject(weatherJsonStr);
    JSONArray daysWeather = weather.getJSONArray("list");
    JSONObject dayWeather = daysWeather.getJSONObject(0);
    JSONObject dayTemperature = dayWeather.getJSONObject("temp");
    int maxTemp = dayTemperature.getDouble("max");

Note that there may has a JSONException when the json tring is invalid, you need to add try-catch for this.

public class WooliesCrawler {

static class Product{
    private int mStockCode;
    private String mName;
    private float mPrice;
    private float mWasPrice;
    private float mCupPrice;
    private String mCupMeasure;
    private boolean mIsAvailable;

    public Product(String name, int stockCode, float price, float wasPrice, float cupPrice, String cupMeasure, boolean isAvailable) {
        mStockCode = stockCode;
        mName = name;
        mPrice = price;
        mWasPrice = wasPrice;
        mCupPrice = cupPrice;
        mCupMeasure = cupMeasure;
        mIsAvailable = isAvailable;
    }

    @Override
    public String toString() {
        return String.format("%s %s %s %s %s", mStockCode, mName, mWasPrice, mPrice, mIsAvailable);
    }
}

public static void downloadProducts(final Context context, final int pageNumber){
    RequestQueue queue = Volley.newRequestQueue(context);

    int groupId = 1018;
    final int pageSize = 100;

    String urlFormat = "https://www.woolworths.com.au/apis/ui/Product/Specials/half-price?GroupID=%s&pageNumber=%s&pageSize=%s";
    String url = String.format(urlFormat, groupId, pageNumber, pageSize);

    StringRequest request = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    List<Product> productList = new ArrayList<>();

                    String text = response;
                    try {
                        JSONObject root = new JSONObject(text);
                        JSONArray items = root.getJSONArray("Items");
                        for (int i = 0; i < items.length(); i++) {
                            JSONObject itemList = (JSONObject) items.get(i);
                            JSONArray products = itemList.getJSONArray("Products");
                            JSONObject productJson = (JSONObject) products.get(0);

                            String name = productJson.getString("Name");
                            int stockCode = productJson.getInt("Stockcode");
                            float price = (float) productJson.getDouble("Price");
                            float wasPrice = (float) productJson.getDouble("WasPrice");
                            String cupMeasure = productJson.getString("CupMeasure");
                            float cupPrice = (float) productJson.getDouble("CupPrice");
                            boolean isAvailable = productJson.getBoolean("IsAvailable");

                            Product product = new Product(name, stockCode, price, wasPrice, cupPrice, cupMeasure, isAvailable);
                            productList.add(product);

                            Timber.d(product.toString());
                        }

                        if(items.length() == pageSize){
                            downloadProducts(context, pageNumber+1);
                        }

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

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Timber.e(error);
                }
    });

    queue.add(request);
}

}

Android

Related Posts

Comments