Java 如何将JSON解析为ListView

Java 如何将JSON解析为ListView,java,android,json,Java,Android,Json,我正在尝试将JSON数据解析到列表中,我希望实现以下目标:- Category List -> Sub-Category List 我的JSON如下所示: [ { "categoryName" : "Killer", "categoryList" : [{"ProductID": "1", "ProductName": "Jeans"},

我正在尝试将JSON数据解析到列表中,我希望实现以下目标:-

Category List -> Sub-Category List
我的JSON如下所示:

[
    {
         "categoryName" : "Killer",
         "categoryList" : [{"ProductID": "1",
                            "ProductName": "Jeans"},
                           {"ProductID": "2",
                            "ProductName": "Tees"}]
   },

   {
         "categoryName" : "Blackberry",
         "categoryList" : [{"ProductID": "1",
                            "ProductName": "Trousers"},
                           {"ProductID": "2",
                            "ProductName": "Shirts"}]
   }    
]
通过使用下面的代码,我能够获取类别列表,CategoryActivity.java

  public class CategoryActivity extends ListActivity {
// Connection detector
ConnectionDetector cd;

// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();

ArrayList<HashMap<String, String>> categoriesList;

// albums JSONArray
JSONArray categories = null;

// albums JSON url
static final String URL_CATEGORIES = "http://domain.it/keyurls/multi.json";

// ALL JSON node names
private static final String CATEGORY_NAME = "categoryName";

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

    cd = new ConnectionDetector(getApplicationContext());

    // Check for internet connection
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(CategoryActivity.this, "Internet Connection Error",
                "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }

    // Hashmap for ListView
    categoriesList = new ArrayList<HashMap<String, String>>();

    // Loading Albums JSON in Background Thread
    new LoadAlbums().execute();

    // get listview
    ListView lv = getListView();

    /**
     * Listview item click listener
     * TrackListActivity will be lauched by passing album id
     * */
    lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                long arg3) {
            // on selecting a single album
            // TrackListActivity will be launched to show tracks inside the album
            Intent i = new Intent(getApplicationContext(), ProductActivity.class);

            // send album id to tracklist activity to get list of songs under that album
            String category_name = ((TextView) view.findViewById(R.id.category_name)).getText().toString();
            i.putExtra("category_name", category_name);             

            startActivity(i);
        }
    });     
}

/**
 * Background Async Task to Load all Albums by making http request
 * */
class LoadAlbums extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(CategoryActivity.this);
        pDialog.setMessage("Listing Categories ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting Categories JSON
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        // getting JSON string from URL
        String json = jsonParser.makeHttpRequest(URL_CATEGORIES, "GET",
                params);

        // Check your log cat for JSON reponse
        Log.d("Categories JSON: ", "> " + json);

        try {               
            categories = new JSONArray(json);

            if (categories != null) {
                // looping through All albums
                for (int i = 0; i < categories.length(); i++) {
                    JSONObject c = categories.getJSONObject(i);

                    // Storing each json item values in variable
                    String name = c.getString(CATEGORY_NAME);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(CATEGORY_NAME, name);

                    // adding HashList to ArrayList
                    categoriesList.add(map);
                }
            }else{
                Log.d("Categories: ", "null");
            }

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

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all albums
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        CategoryActivity.this, categoriesList,
                        R.layout.list_item_category, new String[] { CATEGORY_NAME }, new int[] {
                                R.id.category_name });

                // updating listview
                setListAdapter(adapter);
            }
        });
    }
}
 }
  public class ProductActivity extends ListActivity {
    // Connection detector
    ConnectionDetector cd;

    // Alert dialog manager
    AlertDialogManager alert = new AlertDialogManager();

     // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jsonParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // products JSONArray
    JSONArray products = null;

    // Category name
    String category_name;

    private static final String CATEGORY_NAME = "categoryName";
    private static final String CATEGORY_LIST = "categoryList";
    private static final String PRODUCT_ID = "ProductID";
    private static final String PRODUCT_NAME = "ProductName";

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

        cd = new ConnectionDetector(getApplicationContext());

        // Check if Internet present
        if (!cd.isConnectingToInternet()) {
            // Internet Connection is not present
            alert.showAlertDialog(ProductActivity.this, "Internet Connection Error",
                    "Please connect to working Internet connection", false);
            // stop executing code by return
            return;
        }

        // Get album id
        Intent i = getIntent();
        category_name = i.getStringExtra("category_name");

        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

        // get listview
        ListView lv = getListView();

        /**
         * Listview on item click listener
         * SingleTrackActivity will be lauched by passing album id, song id
         * */
        lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                    long arg3) {

            }
        }); 
    }

     /**
     * Background Async Task to Load all tracks under one album
     * */
    class LoadTracks extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ProductActivity.this);
            pDialog.setMessage("Loading products ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

     /**
     * getting products json and parsing
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        // post category name as GET parameter
        params.add(new BasicNameValuePair(CATEGORY_NAME, category_name));

        // getting JSON string from URL
        String json = jsonParser.makeHttpRequest(CategoryActivity.URL_CATEGORIES, "GET",
                params);

        // Check your log cat for JSON reponse
        Log.d("Product List JSON: ", json);

        try {
            JSONObject jObj = new JSONObject(json);
            if (jObj != null) {
                category_name = jObj.getString(CATEGORY_NAME);
                products = jObj.getJSONArray(CATEGORY_LIST);

                if (products != null) {
                    // looping through All songs
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable
                        String song_id = c.getString(PRODUCT_ID);
                        String name = c.getString(PRODUCT_NAME);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put("category_name", category_name);
                        map.put(PRODUCT_ID, song_id);
                        map.put(PRODUCT_NAME, name);                        

                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    Log.d("Categories: ", "null");
                }
            }

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

        return null;
    }

     /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all tracks
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */

                 ListAdapter adapter = new SimpleAdapter(
                         ProductActivity.this, productsList,
                         R.layout.list_item_product, new String[] { "category_name", PRODUCT_ID, PRODUCT_NAME}, 
                         new int[] {
                                 R.id.album_id, R.id.song_id, R.id.album_name });
                 // updating listview
                 setListAdapter(adapter);

                }
            });
        }
    }
//您需要在urs的循环中添加此项
JSONArray list=newjsonarray=c.getString(类别名称);
对于(int j=0;j
公共类AndroidJSONParsingActivity扩展了ListActivity{
//发出请求的url
专用静态字符串url=”http://10.0.2.2/product.php";
私有静态最终字符串TAG_PRODUCTS=“”;
私有静态最终字符串标记\u ID=“ID”;
私有静态最终字符串标记_PID=“productId”;
私有静态最终字符串标记\u QTY=“productQty”;
私有静态最终字符串标记_PRICE=“productPrice”;
//联系JSONArray
JSONArray产品=null;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//ListView的Hashmap
ArrayList contactList=新建ArrayList();
//创建JSON解析器实例
JSONParser jParser=新的JSONParser();
//从URL获取JSON字符串
JSONObject json=jParser.getJSONFromUrl(url);
试一试{
//获取联系人数组
products=json.getJSONArray(TAG_products);
//通过所有触点循环
对于(int i=0;ivalue
地图放置(标签标识,标识);
映射放置(标签PID,PID);
地图放置(标签数量、数量);
//将哈希列表添加到ArrayList
联系人列表。添加(地图);
}
}捕获(JSONException e){
e、 printStackTrace();
}
/**
*将解析的JSON数据更新到ListView中
* */
ListAdapter=新的SimpleAdapter(此,contactList,
R.layout.list_项目,
新字符串[]{TAG_PID,TAG_数量,TAG_价格},新int[]{
R.id.name、R.id.email、R.id.mobile});
setListAdapter(适配器);
//选择单个ListView项
ListView lv=getListView();
//在选择单个列表项时启动新屏幕
lv.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父级、视图、,
内部位置,长id){
//从选定的ListItem获取值
字符串名称=((TextView)view.findViewById(R.id.name))
.getText().toString();
字符串成本=((TextView)view.findViewById(R.id.email))
.getText().toString();
字符串描述=((TextView)view.findViewById(R.id.mobile))
.getText().toString();
//开始新的意图
Intent in=新的Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(标签号,名称);
额外计价(标签数量、成本);
in.putExtra(标签价格、说明);
星触觉(in);
}
});
}
}

这可能对您有用。

问题出在您的
lv.setOnItemClickListener

换成

lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View view, int arg2,
            long arg3) {
        // on selecting a single album
        // TrackListActivity will be launched to show tracks inside the album
        HashMap<String, String> o=(HashMap<String,String>)lv.getItemAtPosition(Position);       
        Intent i = new Intent(getApplicationContext(), ProductActivity.class);
        i.putExtra("category_name", o.get(category_name));             

        startActivity(i);
    }
});     
lv.setOnItemClickListener(新的android.widget.AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView arg0、View视图、int arg2、,
长arg3){
//关于选择单个唱片集
//将启动TrackListActivity以显示相册中的曲目
HashMap o=(HashMap)lv.getItemAtPosition(位置);
Intent i=新的Intent(getApplicationContext(),ProductActivity.class);
i、 putExtra(“类别名称”,o.get(类别名称));
星触觉(i);
}
});     
希望这有帮助

像这样试试看

    JSONArray arr;
            try {
                arr = new JSONArray("YOUR_JSON");

                for (int i = 0; i < arr.length(); i++) {

                    JSONObject catList = arr.getJSONObject(i);
                    String catName = catList.getString("categoryName");
                    System.out.println("categoryName:" + catName);
                    JSONArray list = catList.getJSONArray("categoryList");
                    for (int j = 0; j < list.length(); j++) {
                        JSONObject subCatList = list.getJSONObject(i);
                        String productID = subCatList.getString("ProductID");
                        String productName = subCatList.getString("ProductName");
                        System.out.println("Sub CatList" + productID + " "
                                + productName);

                    }

                }
            } catch (J

SONException e) {
            e.printStackTrace();
        }
JSONArray-arr;
试一试{
arr=新JSONArray(“您的JSON”);
对于(int i=0;i
当u r循环json对象时,会自动提取suncategory@MTBmonica不清楚yaar,请以清晰的方式显示代码,在将每个json项值存储在variablecool中之后,实际上我试图向您解释那里有嵌套的json数组。。在for循环中,您需要再次创建新的json数组,在该数组中,您需要再次解析其对象
public class AndroidJSONParsingActivity extends ListActivity {

// url to make request
private static String url = "http://10.0.2.2/product.php";

private static final String TAG_PRODUCTS = " ";
private static final String TAG_ID = "Id";
private static final String TAG_PID = "productId";
private static final String TAG_QTY = "productQty";
private static final String TAG_PRICE = "productPrice";
// contacts JSONArray
JSONArray products = null;

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

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);

    try {
        // Getting Array of Contacts
        products = json.getJSONArray(TAG_PRODUCTS);

        // looping through All Contacts
        for (int i = 0; i < products.length(); i++) {
            JSONObject c = products.getJSONObject(i);

            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String pid = c.getString(TAG_PID);
            String qty = c.getString(TAG_QTY);
            String price = c.getString(TAG_PRICE);

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_ID, id);
            map.put(TAG_PID, pid);
            map.put(TAG_QTY, qty);

            // adding HashList to ArrayList
            contactList.add(map);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    /**
     * Updating parsed JSON data into ListView
     * */
    ListAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.list_item,
            new String[] { TAG_PID, TAG_QTY, TAG_PRICE }, new int[] {
                    R.id.name, R.id.email, R.id.mobile });

    setListAdapter(adapter);

    // selecting single ListView item
    ListView lv = getListView();

    // Launching new screen on Selecting Single ListItem
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name))
                    .getText().toString();
            String cost = ((TextView) view.findViewById(R.id.email))
                    .getText().toString();
            String description = ((TextView) view.findViewById(R.id.mobile))
                    .getText().toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    SingleMenuItemActivity.class);
            in.putExtra(TAG_PID, name);
            in.putExtra(TAG_QTY, cost);
            in.putExtra(TAG_PRICE, description);
            startActivity(in);

        }
    });

}

}
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View view, int arg2,
            long arg3) {
        // on selecting a single album
        // TrackListActivity will be launched to show tracks inside the album
        HashMap<String, String> o=(HashMap<String,String>)lv.getItemAtPosition(Position);       
        Intent i = new Intent(getApplicationContext(), ProductActivity.class);
        i.putExtra("category_name", o.get(category_name));             

        startActivity(i);
    }
});     
    JSONArray arr;
            try {
                arr = new JSONArray("YOUR_JSON");

                for (int i = 0; i < arr.length(); i++) {

                    JSONObject catList = arr.getJSONObject(i);
                    String catName = catList.getString("categoryName");
                    System.out.println("categoryName:" + catName);
                    JSONArray list = catList.getJSONArray("categoryList");
                    for (int j = 0; j < list.length(); j++) {
                        JSONObject subCatList = list.getJSONObject(i);
                        String productID = subCatList.getString("ProductID");
                        String productName = subCatList.getString("ProductName");
                        System.out.println("Sub CatList" + productID + " "
                                + productName);

                    }

                }
            } catch (J

SONException e) {
            e.printStackTrace();
        }