Android 需要JSON解析方面的帮助吗

Android 需要JSON解析方面的帮助吗,android,json,android-listview,arrays,Android,Json,Android Listview,Arrays,我的json文件如下所示: { "shops": [ { "id": "11", "name": "Next", "description": "Opened in 2005, offers a selection of clothes, shoes and accessories.", "url": "/shop/550/127", "categories": [

我的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"
      },
.....
我想用“categories”按类别取这个商店。例如,如果男士牛仔裤从列表中单击,则与该类别关联的所有商店都将显示为列表。这个JSON文件存储在SD卡中。当前,如果单击列表项,我可以获取所有商店。但我无法根据类别进行筛选

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;
    }
}
导入java.io.BufferedReader;
导入java.io.File;
导入java.io.FileNotFoundException;
导入java.io.FileReader;
导入java.io.IOException;
导入java.util.HashMap;
导入java.util.List;
导入org.json.JSONObject;
导入com.kabelash.sg.util.ExternalStorage;
导入android.app.Activity;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.Menu;
导入android.widget.ListView;
导入android.widget.simpledapter;
公共课活动{
私有最终字符串JSON\u file=“api\u output\u example.JSON”;
文件jsonFile;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.baby1_1);
/**获取缓存目录*/
文件cDir=ExternalStorage.getSDCacheDir(这是“json_文件”);
/**获取对临时文件的引用(如果先前创建)*/
jsonFile=new文件(cDir.getPath()+“/”+JSON_文件);
字符串strLine=“”;
StringBuilder strJson=新的StringBuilder();
/**正在读取临时文件的内容(如果已存在)*/
试一试{
FileReader fReader=新的FileReader(jsonFile);
BufferedReader bReader=新的BufferedReader(fReader);
/**逐行读取文件的内容*/
而((strLine=bReader.readLine())!=null){
strJson.append(strLine);
}
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
//系统输出打印LN(strJson);
/**开始解析JSON数据*/
新建ListViewLoaderTask().execute(strJson.toString());
}
私有类ListViewLoaderTask扩展异步任务{
JSONObject jObject;
/**在非ui线程中解析JSON数据*/
@凌驾
受保护的SimpleAdapter doInBackground(字符串…strJson){
试一试{
jObject=新的JSONObject(strJson[0]);
CountryJSONParser CountryJSONParser=新的CountryJSONParser();
parse(jObject);
}捕获(例外e){
d(“JSON例外1”,例如toString());
}
CountryJSONParser CountryJSONParser=新的CountryJSONParser();
列表商店=空;
试一试{
/**将解析后的数据作为列表构造获取*/
shops=countryJsonParser.parse(jObject);
}捕获(例外e){
Log.d(“异常”,例如toString());
}
/**Hashmap中使用的键*/
字符串[]from={“shop”、“image”、“description”};
/**listview\u布局中的视图ID*/
int[]to={R.id.tv_country,R.id.iv_flag,R.id.tv_country_details};
/**实例化适配器以存储每个项
*R.layout.listview\u布局定义每个项目的布局
*/
simpledapter adapter=newsimpledapter(getBaseContext(),shops,R.layout.lv_layout,from,to);
返回适配器;
}
/**由Android系统在“doInBackground”上调用,完全执行*/
/**这将在ui线程中执行*/
@凌驾
受保护的void onPostExecute(SimpleAdapter适配器){
/**获取对main.xml布局文件的listview的引用*/
ListView ListView=(ListView)findViewById(R.id.lv_国家);
/**将包含国家/地区列表的适配器设置为listview*/
setAdapter(适配器);
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
getMenuInflater().充气(R.menu.main,menu);
返回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;
    }
}
import java.util.ArrayList;
导入java.util.HashMap;
导入java.util.List;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
公共类CountryJSONParser{
/**接收JSONObject并返回列表*/
公共列表解析(JSONObject jObject){
JSONArray jShops=null;
试试{
/**检索“国家”数组中的所有元素*/
jShops=jObject.getJSONArray(“商店”);
}捕获(JSONException e){
e、 printStackTrace();
}
/**使用json对象数组调用getShops
*其中每个json对象代表一个国家
*/
返回getShops(jShops);
}
私有列表getShops(JSONArray jShops){
int shopCount=jShops.length();
List shopList=new ArrayList();
HashMap-shop=null;
/**获取每个店铺,解析并添加到列表对象*/

对于(int i=0;i首先,我认为您分析它是错误的。“categories”是JsonArray,而您将其作为字符串进行分析。您应该将其作为数组进行分析。因此,它基本上是数组中的一个数组。处理完它后,您可以轻松地根据category值将单个项标记为适当的类别

编辑:

更好的方法是创建一个具有所需属性的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>();
    }

}  
公共类商店{
公共字符串名称;
公共字符串描述;
公共字符串图像;
公共阵列列表类别列表;
公共商店(){
类别列表=新阵列列表
public class Shop{

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

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

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