diwa
diwa

Reputation: 169

Parsing json url

I am trying to create an image view from json url. I am getting the url using a for-loop in a string. I could not use that variable outside the for-loop. I tried constructing an arraylist inside the for-loop. This is what I am getting in the log.

Creating view...[[], [], [], [], [], [], [], [], [], []]

Here is my code.

    @Override
    protected JSONObject doInBackground(String... args) {

        JSONParser jParser = new JSONParser();
        // Getting JSON from URL
        JSONObject json = jParser.getJSONFromUrl(url);

       // Log.v("url", "Creating view..." + json);

        try {

            // Getting JSON Array from URL
            android = json.getJSONArray(TAG_URL);

            for (int i = 0; i < android.length(); i++) {

                map = new ArrayList<HashMap<String, String>>();
                JSONObject c = android.getJSONObject(i);

                String name = c.getString(TAG_URL);

                arraylist.add(map);



              //  Log.v("url", name);
            }
            Log.v("url", "Creating view..." + arraylist);
        } catch (JSONException e) {
            e.printStackTrace();
        }


        return null;

    }

Here is the json: http://www.json-generator.com/api/json/get/ciCLARKtKa?indent=4

Upvotes: 0

Views: 169

Answers (3)

Jitesh Upadhyay
Jitesh Upadhyay

Reputation: 5260

hi do something as follows

JSONObject primaryObject = new JSONObject(//yours json string);
    JSONArray primaryArray = primaryObject.getJSONArray("worldpopulation");
    for (int i = 0; i < primaryArray.length(); i++) {

        JSONObject another = primaryArray.getJSONObject(i);
        String country = another.getString("country");
        String flag = another.getString("flag");
        int rank = another.getInt("rank");
        String population = another.getString("population");

         HashMap<String, String> map = new HashMap<String, String>();
         map.put("flag", flag);
         arraylist.add(i, map);
    }

Upvotes: 1

Leonardo
Leonardo

Reputation: 3191

When in doubt on how to create a POJO from a JSON, I'd recommend you to try this site: http://www.jsonschema2pojo.org/

It outputs you a full java class that works for a given json type;

For most cases I'd recommend you to use this config (from the website above): Source type: Json Annotation style: None And check ONLY use primitives.

Hope it helps !

Upvotes: 1

Android
Android

Reputation: 398

I think you missed put the values into MAP.

Try use like this

for (int i = 0; i < android.length(); i++) {
                JSONObject c = android.getJSONObject(i);
                // Storing each json item in variable
                String flag = c.getString("flag");
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("flag", flag);
                arraylist.add(i, map);

            }

Upvotes: 0

Related Questions