把JSON数据转换成一个列表 [英] Putting JSON data into a List

查看:145
本文介绍了把JSON数据转换成一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的JSON数据从我的服务器即将正确,我只想把它分为以下几个数组,但我不知道JSON数据被正确地插入到ArrayList中。

下面是数组

 私人列表< ShopInfo> createList(INT尺寸){
    名单< ShopInfo>结果=新的ArrayList< ShopInfo>();
    的for(int i = 1; I< =大小;我++){
        ShopInfo CI =新ShopInfo();
        ci.name = TAG_NAME + I;
        ci.address = TAG_ADDRESS + I;
        result.add(CI);
    }
    返回结果;
}
 

我的JSON

  {成功:1,店:[{名:Test_Shop,地址:大1路都柏林}
 

文件

 公共类OrderCoffee延伸活动{

JSONParser jParser =新JSONParser();
ArrayList的< HashMap的<字符串,字符串>> shopList;
私有静态字符串url_all_products =XXXXXXXXXX / ordercoffee.php;
//产品JSONArray
JSONArray商店= NULL;


// JSON节点名称
私有静态最后弦乐TAG_SUCCESS =成功;
私有静态最后弦乐TAG_SHOPS =商店;
私有静态最后弦乐TAG_NAME =名;
私有静态最后弦乐TAG_ADDRESS =地址;


//取得的在当地参与咖啡店正在使用的应用程序的列表
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.order_coffee);
    新LoadAllProducts()执行();
    RecyclerView recList =(RecyclerView)findViewById(R.id.cardList);
    recList.setHasFixedSize(真正的);
    LinearLayoutManager LLM =新LinearLayoutManager(本);
    llm.setOrientation(LinearLayoutManager.VERTICAL);
    recList.setLayoutManager(LLM);
    shopList =新的ArrayList< HashMap的<字符串,字符串>>();
    ShopAdapter CA =新ShopAdapter(createList(3));
    recList.setAdapter(CA);

}


类LoadAllProducts扩展的AsyncTask<字符串,字符串,字符串> {


    @覆盖
    保护字符串doInBackground(字符串参数... args){
        //大厦参数
        名单<的NameValuePair> PARAMS =新的ArrayList<的NameValuePair>();
        //从URL获取JSON字符串
        JSONObject的JSON = jParser.makeHtt prequest(url_all_products,GET,则params);

        //检查你的日志猫JSON效应初探
        Log.d(所有产品,json.toString());

        尝试 {
            //检查成功TAG
            INT成功= json.getInt(TAG_SUCCESS);

            如果(成功== 1){
                发现//产品
                //获取数组
                商店= json.getJSONArray(TAG_SHOPS);

                //遍历所有产品
                的for(int i = 0; I< shops.length();我++){
                    JSONObject的C = shops.getJSONObject(我);

                    //保存在变量中的每个JSON项目
                    字符串ID = c.getString(TAG_ADDRESS);
                    字符串名称= c.getString(TAG_NAME);

                    //创建新的HashMap
                    HashMap的<字符串,字符串>图=新的HashMap<字符串,字符串>();

                    //添加每个子节点HashMap中的key =>值
                    map.put(TAG_ADDRESS,ID);
                    map.put(TAG_NAME,姓名);

                    shopList.add(图)


                }
            } 其他 {
            }
        }赶上(JSONException E){
            e.printStackTrace();
        }

        返回null;
    }


}

@覆盖
公共布尔onCreateOptionsMenu(功能菜单){
    返回true;
}

@覆盖
公共布尔onOptionsItemSelected(菜单项项){
    //处理动作栏项目点击这里。将操作栏
    //自动在主/向上按钮操作的点击,只要
    //你在AndroidManifest.xml中指定一个父活动。
    INT的id = item.getItemId();
    如果(ID == R.id.action_settings){
        返回true;
    }
    返回super.onOptionsItemSelected(项目);
}


私人列表< ShopInfo> createList(INT尺寸){
    名单< ShopInfo>结果=新的ArrayList< ShopInfo>();
    的for(int i = 1; I< =大小;我++){
        ShopInfo CI =新ShopInfo();
        ci.name = TAG_NAME + I;
        ci.address = TAG_ADDRESS + I;
        result.add(CI);
    }
    返回结果;
}
}
 

ShopAdapter

 包com.example.strobe.coffeetime;

进口android.support.v7.widget.RecyclerView;
进口android.view.LayoutInflater;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.TextView;

进口的java.util.List;

/ **
 *在15年10月4日创建于根。
 * /
公共类ShopAdapter扩展RecyclerView.Adapter< ShopAdapter.ShopViewHolder> {

    私人列表< ShopInfo> shopList;

    公共ShopAdapter(名单< ShopInfo> shopList){
        this.shopList = shopList;
    }


    @覆盖
    公众诠释getItemCount(){
        返回shopList.size();
    }

    @覆盖
    公共无效onBindViewHolder(ShopViewHolder shopViewHolder,int i)以{
        ShopInfo CI = shopList.get(我);
        shopViewHolder.vName.setText(ci.name);
        shopViewHolder.vAddress.setText(ci.address);

    }

    @覆盖
    公共ShopViewHolder onCreateViewHolder(ViewGroup中的ViewGroup,int i)以{
        查看ItemView控件= LayoutInflater。
                从(viewGroup.getContext())。
                膨胀(R.layout.card_layout,ViewGroup中,假);

        返回新ShopViewHolder(ItemView控件);
    }

    公共静态类ShopViewHolder扩展RecyclerView.ViewHolder {

        受保护的TextView vName;
        受保护的TextView将Vaddress;


        公共ShopViewHolder(视图v){
            超级(五);
            vName =(TextView中)v.findViewById(R.id.name);
            将Vaddress =(TextView中)v.findViewById(R.id.address);

        }
    }
}
 

解决方案

您应该改变你的onCreate本

 私人RecyclerView recList;
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.order_coffee);
    recList =(RecyclerView)findViewById(R.id.cardList);
    recList.setHasFixedSize(真正的);
    recList.setLayoutManager(新LinearLayoutManager(本));
    shopList =新的ArrayList< HashMap的<字符串,字符串>>();
    新LoadAllProducts()执行();
}
 

然后在onPostExecute

 保护无效onPostExecute(字符串结果){
    名单< ShopInfo>名单=新的ArrayList< ShopInfo>();
    的for(int i = 0; I< shopList.size();我++){
        ShopInfo CI =新ShopInfo();
        HashMap的<字符串,字符串>地图= shopList.get(I)
        ci.name = map.get(TAG_NAME);
        ci.address = map.get(TAG_ADDRESS);
        list.add(CI);
    }

    ShopAdapter CA =新ShopAdapter(名单);
    recList.setAdapter(CA);
}
 

如果您不使用shopList为别的,你可以将其删除,移动code,用于创建传递给适配器doInBackground名单

I have my JSON data coming correctly from my server, I just want to put it into the following array but I'm not sure the JSON data is correctly being inserted into the ArrayList.

Here is the array

private List<ShopInfo> createList(int size)  {
    List<ShopInfo> result = new ArrayList<ShopInfo>();
    for (int i = 1; i <= size; i++) {
        ShopInfo ci = new ShopInfo();
        ci.name =    TAG_NAME+i;
        ci.address = TAG_ADDRESS+i;
        result.add(ci);
    }
    return result;
}

My json

{"success":1,"shops":[{"name":"Test_Shop","address":"1 Big Road Dublin"}

The file

public class OrderCoffee extends Activity {

JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> shopList;
private static String url_all_products = "xxxxxxxxxx/ordercoffee.php";
// products JSONArray
JSONArray shops = null;


// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_SHOPS = "shops";
private static final String TAG_NAME = "name";
private static final String TAG_ADDRESS = "address";


//get a list of participating coffee shops in the locality that are using the app
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.order_coffee);
    new LoadAllProducts().execute();
    RecyclerView recList = (RecyclerView) findViewById(R.id.cardList);
    recList.setHasFixedSize(true);
    LinearLayoutManager llm = new LinearLayoutManager(this);
    llm.setOrientation(LinearLayoutManager.VERTICAL);
    recList.setLayoutManager(llm);
    shopList = new ArrayList<HashMap<String, String>>();
    ShopAdapter ca = new ShopAdapter(createList(3));
    recList.setAdapter(ca);

}


class LoadAllProducts extends AsyncTask<String, String, String> {


    @Override
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array
                shops = json.getJSONArray(TAG_SHOPS);

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

                    // Storing each json item in variable
                    String id = c.getString(TAG_ADDRESS);
                    String name = c.getString(TAG_NAME);

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

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

                    shopList.add(map);


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

        return null;
    }


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}


private List<ShopInfo> createList(int size)  {
    List<ShopInfo> result = new ArrayList<ShopInfo>();
    for (int i = 1; i <= size; i++) {
        ShopInfo ci = new ShopInfo();
        ci.name =    TAG_NAME+i;
        ci.address = TAG_ADDRESS+i;
        result.add(ci);
    }
    return result;
}
}

ShopAdapter

  package com.example.strobe.coffeetime;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

/**
 * Created by root on 10/04/15.
 */
public class ShopAdapter extends RecyclerView.Adapter<ShopAdapter.ShopViewHolder> {

    private List<ShopInfo> shopList;

    public ShopAdapter(List<ShopInfo> shopList) {
        this.shopList = shopList;
    }


    @Override
    public int getItemCount() {
        return shopList.size();
    }

    @Override
    public void onBindViewHolder(ShopViewHolder shopViewHolder, int i) {
        ShopInfo ci = shopList.get(i);
        shopViewHolder.vName.setText(ci.name);
        shopViewHolder.vAddress.setText(ci.address);

    }

    @Override
    public ShopViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View itemView = LayoutInflater.
                from(viewGroup.getContext()).
                inflate(R.layout.card_layout, viewGroup, false);

        return new ShopViewHolder(itemView);
    }

    public static class ShopViewHolder extends RecyclerView.ViewHolder {

        protected TextView vName;
        protected TextView vAddress;


        public ShopViewHolder(View v) {
            super(v);
            vName =  (TextView) v.findViewById(R.id.name);
            vAddress = (TextView)  v.findViewById(R.id.address);

        }
    }
}

解决方案

You should change your onCreate to this

private RecyclerView recList;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.order_coffee);
    recList = (RecyclerView) findViewById(R.id.cardList);
    recList.setHasFixedSize(true);
    recList.setLayoutManager(new LinearLayoutManager(this));
    shopList = new ArrayList<HashMap<String, String>>();
    new LoadAllProducts().execute();
}

And then in onPostExecute

protected void onPostExecute(String result) {
    List<ShopInfo> list = new ArrayList<ShopInfo>();
    for (int i = 0; i < shopList.size(); i++) {
        ShopInfo ci = new ShopInfo();
        HashMap<String, String> map = shopList.get(i)
        ci.name =    map.get(TAG_NAME);
        ci.address = map.get(TAG_ADDRESS);
        list.add(ci);
    }

    ShopAdapter ca = new ShopAdapter(list);
    recList.setAdapter(ca);
}

If you are not using shopList for anything else you can remove it and move the code for creating the list you pass to the adapter to doInBackground

这篇关于把JSON数据转换成一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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