0

我有这样的json文件:

{
   "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"
      },
.....

我想根据使用“类别”的类别来获取这些商店。例如,如果从列表中单击男士牛仔裤,则与该类别关联的所有商店都显示为列表。而这个 JSON 文件存储在 sdcard 中。目前,如果单击列表项,我可以获取所有商店。但我无法根据类别进行过滤。

让.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;
    }
}

上面给出的代码工作正常,但我想知道如何过滤它。我想使用“bg_image”链接在listview上显示图像(图像存储在sdcard上)。有人可以根据我的要求编辑此代码吗?(不幸的是,我在 Google 上找不到任何有用的东西)。请帮忙!

编辑:现在我尝试做这样的事情,但做错了。

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;
    }
}

需要进一步的帮助。谢谢。

4

1 回答 1

1

首先,我认为您解析错误。'categories' 是 JsonArray,而您将其解析为字符串。你应该把它作为一个数组来做。所以,它基本上是一个数组内的数组。完成后,您可以根据类别值轻松地将单个项目标记为适当的类别。

编辑:

更好的方法是创建具有所需属性的 Shop 对象,然后在 JSON 解析函数中填充 Shop 对象列表。例如

public class Shop{

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

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

}  

这是您修改后的 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;
    }  
}
于 2013-08-19T07:32:12.383 回答