需要在JSON解析帮助 [英] Need help on JSON parsing

查看:185
本文介绍了需要在JSON解析帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样我的JSON文件:

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

我要根据使用类别的类别,以获取该商店。例如,如果男人的牛仔裤从列表点击,则与该类别相关联的所有商店显示为列表。而这个JSON文件存储在SD卡。目前,我能够获取所有的商店,如果列表项点击。但我不能按类别进行过滤。

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

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

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

上面给出的code做工精细,但我想知道如何对其进行过滤。我想用bg_image链接(图像存储在SD卡),显示在列表视图图像。可有人请根据我的要求修改此code? (不幸的是我无法找到任何有用的谷歌)。请帮帮忙!

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.

推荐答案

首先,我觉得你分析是错误的。 类别是JsonArray,而你解析它作为一个字符串。你应该做它作为一个数组。所以,它的基本的阵列内的阵列。一旦你用它做,你可以轻松地标记单个项目作为基于类别值的相应类别。

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.

编辑:

一个更好的方式来做到这一点是创建具有所需属性的店铺对象,然后填充铺对象的名单在你的JSON解析功能。例如

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. e.g

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:

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

这篇关于需要在JSON解析帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆