简体   繁体   中英

Need help on JSON parsing

I have my json file like this:

{
   "shops": [
      {
         "id": "11",
         "name": "Next",
         "description": "Opened in 2005, offers a selection of clothes, shoes and accessories.",
         "url": "/shop/550/127",
         "categories": [
            "4",
            "33",
            "34",
            "16"
         ],
         "bg_image": "/uploads/static/shop/460px/2012/12/5385-127-sale.jpg"
      },
.....

I want to fetch this shops according to the categories using "categories". For example if the men's jeans clicked from the list, then all shops associated with that categories displayed as a list. And this JSON file stored in sdcard. Currently I am able to fetch all the shops if a list item clicked. But I couldn't filter according to the categories.

Jean.java

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import com.kabelash.sg.util.ExternalStorage;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class Jeans extends Activity {
    private final String JSON_file = "api_output_example.json";
    File jsonFile;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.baby1_1);

        /** Getting Cache Directory */
        File cDir = ExternalStorage.getSDCacheDir( this, "json_files" );

        /** Getting a reference to temporary file, if created earlier */
        jsonFile = new File(cDir.getPath() + "/" + JSON_file) ;

        String strLine="";
        StringBuilder strJson = new StringBuilder();

        /** Reading contents of the temporary file, if already exists */
        try {
            FileReader fReader = new FileReader(jsonFile);
            BufferedReader bReader = new BufferedReader(fReader);

            /** Reading the contents of the file , line by line */
            while( (strLine=bReader.readLine()) != null  ){
                strJson.append(strLine);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }


     //System.out.println(strJson);

        /** Start parsing JSON data */
        new ListViewLoaderTask().execute(strJson.toString());

    }


    private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{

        JSONObject jObject;
        /** Doing the parsing of JSON data in a non-ui thread */
        @Override
        protected SimpleAdapter doInBackground(String... strJson) {
            try{
                jObject = new JSONObject(strJson[0]);
                CountryJSONParser countryJsonParser = new CountryJSONParser();
                countryJsonParser.parse(jObject);
            }catch(Exception e){
                Log.d("JSON Exception1",e.toString());
            }

            CountryJSONParser countryJsonParser = new CountryJSONParser();

            List<HashMap<String, String>> shops = null;

            try{
                /** Getting the parsed data as a List construct */
                shops = countryJsonParser.parse(jObject);
            }catch(Exception e){
                Log.d("Exception",e.toString());
            }

            /** Keys used in Hashmap */
            String[] from = { "shop","image","description"};

            /** Ids of views in listview_layout */
            int[] to = { R.id.tv_country,R.id.iv_flag,R.id.tv_country_details};

            /** Instantiating an adapter to store each items
            *  R.layout.listview_layout defines the layout of each item
            */
            SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), shops, R.layout.lv_layout, from, to);

            return adapter;
        }

        /** Invoked by the Android system on "doInBackground" is executed completely */
        /** This will be executed in ui thread */
        @Override
        protected void onPostExecute(SimpleAdapter adapter) {

            /** Getting a reference to listview of main.xml layout file */
            ListView listView = ( ListView ) findViewById(R.id.lv_countries);

            /** Setting the adapter containing the country list to listview */
            listView.setAdapter(adapter);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

countryJSONParser.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class CountryJSONParser {

    /** Receives a JSONObject and returns a list */
    public List<HashMap<String,String>> parse(JSONObject jObject){      

        JSONArray jShops = null;
        try {           
            /** Retrieves all the elements in the 'countries' array */
            jShops = jObject.getJSONArray("shops");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /** Invoking getShops with the array of json object
         * where each json object represent a country
         */
        return getShops(jShops);
    }


    private List<HashMap<String, String>> getShops(JSONArray jShops){
        int shopCount = jShops.length();
        List<HashMap<String, String>> shopList = new ArrayList<HashMap<String,String>>();
        HashMap<String, String> shop = null;    

        /** Taking each shop, parses and adds to list object */
        for(int i=0; i<shopCount;i++){
            try {
                /** Call getShop with shop JSON object to parse the shop */
                shop = getShop((JSONObject)jShops.get(i));
                shopList.add(shop);

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

        return shopList;
    }

    /** Parsing the shop JSON object */
    private HashMap<String, String> getShop(JSONObject jShop){

        HashMap<String, String> shop = new HashMap<String, String>();
        String shopName = "";
        String image="";
        String description = "";
        String categories = "";
        //String capital = "";      

        try {
            shopName = jShop.getString("name");
            image = jShop.getString("bg_image_small");
            description = jShop.getString("description");
            categories = jShop.getString("categories");

            String details =        "Description : " + description;
            //if (categories.equals("11")){
            shop.put("shop", shopName);
            shop.put("image", image);
            shop.put("description", details);
            shop.put("categories", categories);
            //}
        } catch (JSONException e) {         
            e.printStackTrace();
        }       
        return shop;
    }
}

The above given code work fine but I want to know how to filter it. and I want to display images on listview using "bg_image" link (the images are stored on sdcard). Can someone please edit this code according to my requirement? (Unfortunately I couldn't find anything useful on Google). Please help!

Edited: Now I tried to do something like this but couldn't get it right.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ShopJSONParser {
    public class Shop { 
        public String name;
        public String category;
        public String description;
        public String image;
        public ArrayList<String> category_list;
    } 
    /** Receives a JSONObject and returns a list */
    public List<HashMap<String,String>> parse(JSONObject jObject){      

        JSONArray jShops = null;
        try {           
            // Retrieves all the elements in the 'shops' array
            jShops = jObject.getJSONArray("shops");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // Invoking getShops with the array of json object
        // where each json object represent a shop
        return getShops(jShops);
    }

    ArrayList<Shop> shops_array = new ArrayList<Shop>();
    private List<HashMap<String, String>> getShops(JSONArray jShops){
        int shopCount = jShops.length();
        List<HashMap<String, String>> shopList = new ArrayList<HashMap<String,String>>();
        HashMap<String, String> shop = null;    

        /** Taking each shop, parses and adds to list object */
        for (int i = 0; i < jShops.length(); i++) {
            JSONObject Shop_json_obj = jShops.getJSONObject(i);
            Shop shop1 = new Shop();

            String name = Shop_json_obj.getString("name");
            String description = Shop_json_obj.getString("description");

            shop1.name = name;
            shop1.description = description;

            shop1.category_list = new ArrayList<String>();
            JSONArray categories_json_array = null;

            categories_json_array = shop1.getJSONArray("categories");

            for (int j = 0; j < categories_json_array.length(); j++) {

                String cat = categories_json_array.getString(j);
                shop1.category_list.add(cat);
            }

            shops_array.add(shop1);

        }

        return shopList;
    }

    /** Parsing the shop JSON object */
    private HashMap<String, String> getShop(JSONObject jShop){

        HashMap<String, String> shop = new HashMap<String, String>();
        String shopName = "";
        String image="";
        String description = "";
        String categories = "";

        try {
            shopName = jShop.getString("name"); 
            image = jShop.getString("bg_image_small");
            description = jShop.getString("description");
            categories = jShop.getJSONArray("categories").toString();
            System.out.println(categories);
            String details =        "Description : " + description;
            //if (categories.equals("13")){
            shop.put("shop", shopName);
            shop.put("image", image);
            //shop.put("description", details);
            //shop.put("categories", categories);
            //}
        } catch (JSONException e) {         
            e.printStackTrace();
        }       
        return shop;
    }
}

Further help required. Thanks.

Firstly, i think you are parsing it wrong. 'categories' is JsonArray while you are parsing it as a string. You should be doing it as an array. so, its basically an array inside an array. Once you are done with it, you could easily tag an individual item as the appropriate category based on the category value.

Edit:

A better way to do that would be to create a Shop object with desired attributes and then Populate a List of Shop objects in your JSON parsing function. eg

public class Shop{

    public String name;
    public String description;
    public String image;
    public ArrayList<String> category_list;

    public Shop(){
        category_list = new ArrayList<String>();
    }

}  

and here is your modified CountryJSONParser :

import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class CountryJSONParser {

    /** Receives a JSONObject and returns a list */
    public ArrayList<Shop> parse(JSONObject jObject){      

        JSONArray jShops = null;
        try {           
            /** Retrieves all the elements in the 'countries' array */
            jShops = jObject.getJSONArray("shops");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /** Invoking getShops with the array of json object
         * where each json object represent a country
         */
        return getShops(jShops);
    }

    private ArrayList<Shop> getShops(JSONArray jShops){
        int shopCount = jShops.length();
        ArrayList<Shop> shops_array = new ArrayList<Shop>();
        Shop shop = new Shop();

        /** Taking each shop, parses and adds to list object */
        for(int i=0; i<shopCount;i++){
            try {
                /** Call getShop with shop JSON object to parse the shop */
                shop = getShop((JSONObject)jShops.get(i));
                //shopList.add(shop);
                shops_array.add(shop);

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

        return shops_array;
    }

    /** Parsing the shop JSON object */
    private Shop getShop(JSONObject jShop){

        Shop shop = new Shop();   

        try {
        shop.name = jShop.getString("name");
            shop.image = jShop.getString("bg_image_small");
            String details =        "Description : " + shop.description;
            shop.description = details;

            shop.category_list = new ArrayList<String>();
            JSONArray categories_json_array = null;

            categories_json_array = jShop.getJSONArray("categories");

            for (int j = 0; j < categories_json_array.length(); j++) {

                String cat = categories_json_array.getString(j);
                shop.category_list.add(cat);
            }

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

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