dev_ dev_ - 2 months ago 13
Java Question

How to set JSON element tag into ListView?

I have this JSON file and I must put each value of tag "info" into a ListView with click to open the url value in a WebView. The ActionBar title is set with value of the "title" JSON tag.

{
"mobiledata": {
"geoJson_1": "http://###.###.###",
"geoJson_2": "",
"info": [
{
"title": "Italia",
"uri": "https://mysite.wordpress.com/i/"
},
{
"title": "Il tempo",
"uri": "https://mysite.wordpress.com/il/"
},
{
"title": "Le info",
"uri": "https://mysite.wordpress.com/la-terra/"
},
{
"title": "Il rischio",
"uri": "https://mysite.wordpress.com/italia/regioni-italiane/"
},
{
"title": "Le Rubriche mensili",
"uri": "https://mysite.wordpress.com/tag/rubricamensile/"
}
]
}


}

How can I do this? Any help or examples?

Answer

Update

Approach given in old answer is too verbose. Steps to improve:

  1. Use Gson library, it's fast and compact. Add into your module-level build.gradle file:

    dependencies {
        // your dependencies: AppCompat, HTTP client etc
        compile 'com.google.code.gson:gson:2.7'
    }
    
  2. Declare appropriate data structure:

    class InfoItem {
        String title;
        String uri;
    }
    
  3. Parse data:

    JsonElement data = new JsonParser().parse(json);
    
  4. Get mobiledata.info:

    JsonArray info = data
            .getAsJsonObject() // treat parsed data as map
            .getAsJsonObject("mobiledata") // get 'mobiledata' as map
            .getAsJsonArray("info"); // get 'info' as list
    
  5. map parsed jsonObjects into POJOs

    List<InfoItem> items = new Gson()
            .fromJson(info, new TypeToken<List<InfoItem>>(){}.getType());
    
  6. Use your own adapter. With ViewHolder pattern binding will look like this:

    InfoItem item = items.get(position);
    holder.title.setText(item.title);
    holder.uri.setText(item.uri);
    

P. S. You may cache this ugly TypeToken:

    private static final Type type = 
            new TypeToken<List<InfoItem>>(){}.getType();

Full code to test:

    public class SoJsonAnswer {

        private static final Type type = 
                new TypeToken<List<InfoItem>>(){}.getType();

        public static void main(String[] args) {
            String json = "{paste it here}";
            JsonElement data = new JsonParser().parse(json);

            JsonArray info = data
                    .getAsJsonObject() // treat parsed data as map
                    .getAsJsonObject("mobiledata") // get map
                    .getAsJsonArray("info"); // get list

            // map parsed jsonObjects into POJOs
            List<InfoItem> items = new Gson().fromJson(info, type);

            System.out.println(items);
        }

    }

    class InfoItem {
        String title;
        String uri;

        @Override
        public String toString() {
            return "title=" + title + ", uri=" + uri;
        }
    }

Original answer

  1. Include a JSON library in your project. I use this: https://code.google.com/p/json-simple/downloads/list

  2. Parse as object.

    String json = "{...}"; //Your JSON here
    JSONParser parser = new JSONParser(); //Can cause ParseException
    JSONObject obj = (JSONObject) parser.parse(json); //Can cause ClassCastException
    
  3. Get inner data.

    JSONObject mobileData = (JSONObject) obj.get("mobiledata");
    JSONArray info = (JSONArray) mobileData.get("info");
    
  4. Pack this data into an ArrayList. Just use for cycle, get your items and cast them to String.

    ArrayList<Map<String, Object>> data = new ArrayList<>(info.size());
    Map<String, Object> m;
    JSONObject current;
    for (int i = 0; i < info.size(); i++) {
      m = new HashMap<String, Object>();
      current = (JSONObject) info.get(i);
    
      m.put("title", (String) current.get("title"));
      m.put("url", (String) current.get("url"));
      data.add(m);
    }
    
  5. Set Adapter for a ListView.

    String[] from = { "title", "url" };
    int[] to = { android.R.id.text1, android.R.id.text2 };
    
    SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2,
    from, to);
    lvList.setAdapter(adapter);
    

Hope it helps. Code not tested.

Comments