首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从PARSing JSON到ListView

从PARSing JSON到ListView
EN

Stack Overflow用户
提问于 2011-06-16 05:36:16
回答 3查看 3.2K关注 0票数 2

好的,我已经在PARSing我的JSON结果上看了一大堆的例子,但都没有成功。我有下面的JSON示例,我现在不想要状态信息或geoLocation。我只想使用stations对象,并从数组中选取一些内容作为列表显示在我的ListView中。我不理解外面的任何文档。

有没有人可以提供一个简单的例子,说明如何读取JSON并将其放入ListView。这将是非常有用的。我真的没有编写任何代码,因为这些代码都不能真正为我工作。

代码语言:javascript
复制
{
"status": {
    "error": "NO",
    "code": 200,
    "description": "none",
    "message": "Request ok"
},
"geoLocation": {
    "city_id": "147",
    "city_long": "Saint-Laurent",
    "region_short": "QC",
    "region_long": "Quebec",
    "country_long": "Canada",
    "country_id": "43",
    "region_id": "35"
},
"stations": [
    {
        "country": "Canada",
        "reg_price": "N\/A",
        "mid_price": "N\/A",
        "pre_price": "N\/A",
        "diesel_price": "N\/A",
        "address": "3885, Boulevard de la C\u00f4te-Vertu",
        "diesel": "0",
        "id": "33862",
        "lat": "45.492367",
        "lng": "-73.710915",
        "station": "Shell",
        "logo": "http:\/\/www.mygasfeed.com\/img\/station-logo\/logo-shell.png",
        "region": "Quebec",
        "city": "Saint-Laurent",
        "reg_date": "N\/A",
        "mid_date": "N\/A",
        "pre_date": "N\/A",
        "diesel_date": "N\/A",
        "distance": "1.9km"
    }
]
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-06-16 06:13:31

下面是一个如何解析数组并将其显示在列表视图中的示例。我没有包含xml,但是描述包含country和address (或其他任何内容)的txt字段的listview和多行结果非常简单:

代码语言:javascript
复制
 String[] from = new String[] {"row_1", "row_2"};
 int[] to = new int[] { R.id.country, R.id.address};
 List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();

try {
     JSONObject obj = new JSONObject(jsonString);
     JSONArray stations = obj.getJSONArray("stations");
     Log.i(TAG,"Number of entries " + stations.length());
     for (int j = 0; j < stations.length(); j++) {
             JSONObject jsonObject = stations.getJSONObject(j);
             HashMap<String, String> map = new HashMap<String, String>();
             map.put("row_1", jsonObject.getString("country"));
             map.put("row_2", jsonObject.getString("address"));

             fillMaps.add(map);
     }
 } catch (Exception e) {
        e.printStackTrace();
 }

 SimpleAdapter adapter = new SimpleAdapter(context, fillMaps, R.layout.result, from, to);
 mListView.setAdapter(adapter);
票数 3
EN

Stack Overflow用户

发布于 2011-06-16 05:56:39

首先,像这样解析您的JSON对象:

代码语言:javascript
复制
String str_json = "your json string";
try {
    JSONObject obj = new JSONObject(str_json);
    JSONArray stations = obj.getJSONArray("stations");
    //etc etc...

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

然后将此JSONArray解析为您已创建的自定义Station对象的ArrayList,例如:

代码语言:javascript
复制
public class Station {

    public String country;
    public int reg_price;
    // etc etc...
}

将JSONArray中的项目放入ArrayList中:

代码语言:javascript
复制
ArrayList<Station> stationsArrList = new ArrayList<Station>();

int len = stations.size();    
for ( int i = 0; i < len; i++ ){
    JSONObject stationObj = stations.getJSONObject(i);
    Station station = new Station();

    for ( int j = 0; j < stationObj.len(); j++ ){
        //add items from stationObj to station
    }
    stationsArrList.add(station);
}

然后创建一个适配器(假设您希望显示两条以上的信息):

代码语言:javascript
复制
public class StationListAdapter extends BaseAdapter {
    private static ArrayList<Station> stationArrayList;

    private LayoutInflater inflator;

    public StationListAdapter(Context context, ArrayList<Station> results) {
        stationArrayList = results;
        inflator = LayoutInflater.from(context);
    }

    public int getCount() {
        if (stationArrayList == null)
            return 0;
        else
            return stationArrayList.size();
    }

    public Object getItem(int position) {
        try {
            return stationArrayList.get(position);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = inflator.inflate(R.layout.list_item_station, null);
            holder = new ViewHolder();
            holder.country = (TextView) convertView.findViewById(R.id.station_listview_item_one);
            holder.reg_price = (TextView) convertView.findViewById(R.id.station_listview_item_two);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.country.setText(stationArrayList.get(position).getCountry());
        holder.reg_price.setText( stationArrayList.get(position).getRegPrice());

        return convertView;
    }

    static class ViewHolder {
        TextView country;
        TextView reg_price;
        //etc
    }
}

在适配器中,您将使用为每个列表行定义的listview xml布局。

最后,获取对列表的引用,并在主活动代码中添加数据:

代码语言:javascript
复制
stationList = (ListView) findViewById(R.id.station_list_view);
stationListAdapter = new StationListAdapter(this, stationsArrList);
stationList.setAdapter(stationListAdapter);
票数 6
EN

Stack Overflow用户

发布于 2013-04-24 15:48:07

代码语言:javascript
复制
public class JSONParsingExampleActivity extends Activity {
/** Called when the activity is first created. */

 private ArrayList<String> id;
 private ArrayList<String> name;
 private ArrayList<String> email;
 private ArrayList<String> address;
 private ArrayList<String> gender;
 private ArrayList<String> mobile;
 private ArrayList<String> home;
 private ArrayList<String> office;
 ListView view;
 ProgressDialog mDialog=null;       // Thread code
 private Runnable viewOrders;   // Thread code
 private Thread thread1;

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

    id=new ArrayList<String>();
    name=new ArrayList<String>();
    email=new ArrayList<String>();
    address=new ArrayList<String>();
    gender=new ArrayList<String>();
    mobile=new ArrayList<String>();
    home=new ArrayList<String>();
    office=new ArrayList<String>();
    view = (ListView)findViewById(R.id.listview);
    mDialog=new ProgressDialog(this);   // Thread code
    mDialog.setMessage("Loading....");


    viewOrders =new Runnable()  // Thread code
    {
        public void run()       // Thread code
        {
            Json_function();
            runOnUiThread(returnRes);
        }
    };
    thread1=new Thread(null,viewOrders,"Bacground");
    thread1.start();
    mDialog.show();
}

private Runnable returnRes=new Runnable()   // Thread code
{

    @Override
    public void run()   // Thread code 
    {
    mDialog.cancel();

        for(int i=0;i<id.size();i++)
        {
            System.out.println("==========================");
            System.out.println("id : - " +id.get(i));
            System.out.println("name : - " +name.get(i));
            System.out.println("email : - " +email.get(i));
            System.out.println("address : - " +address.get(i));
            System.out.println("gender : - " +gender.get(i));
            System.out.println("mobile : - " +mobile.get(i));
            System.out.println("home : - " +home.get(i));
            System.out.println("office : - " +office.get(i));
        }   

        ArrayAdapter<String> adapter= new ArrayAdapter<String>(JSONParsingExampleActivity.this, android.R.layout.simple_list_item_1, name);

        view.setAdapter(new CustomAdapter(JSONParsingExampleActivity.this));        
    }       
};

private void Json_function() 
{
    String result=null;

    try
    {
        result=getDataFromWebService("http://api.androidhive.info/contacts/");
        System.out.println("length old--> " +result);
    }
    catch(Exception e)
    {

    }
    try
    {
        JSONObject json_data=new JSONObject(result);
        JSONArray json_array=json_data.getJSONArray("contacts");
        System.out.println("json array length : - " +json_array.length());

        for(int i=0;i<json_array.length();i++)
        {
            json_data=json_array.getJSONObject(i);

            id.add(json_data.getString("id"));
            name.add(json_data.getString("name"));
            email.add(json_data.getString("email"));
            address.add(json_data.getString("address"));
            gender.add(json_data.getString("gender"));

            String str= json_data.getString("phone");
            JSONObject json_data1 = new JSONObject(str);

            mobile.add(json_data1.getString("mobile"));
            home.add(json_data1.getString("home"));
            office.add(json_data1.getString("office"));
        }
    }
    catch(Exception e1)
    {
        e1.printStackTrace();
    }
}

public static String getDataFromWebService(String strUrl)
{
    StringBuffer strBuffer=new StringBuffer();
    InputStream is=null;

    try
    {
        System.out.println("getdata from web service url:--> " +strUrl);

        HttpClient httpclient=new DefaultHttpClient();
        HttpPost httppost=new HttpPost(strUrl);

        HttpResponse httpresponse=httpclient.execute(httppost);
        HttpEntity httpentity=httpresponse.getEntity();

        is=httpentity.getContent();

        int in=httpresponse.getStatusLine().getStatusCode();
        System.out.println("Response code:--> " +in);
    }
    catch(Exception e)
    {
        Log.e("log_tag", "Eroor in http connection" +e.toString());
    }
    try
    {
        int ch;

        while((ch=is.read())!=-1)
            strBuffer.append((char)ch);

        is.close();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return strBuffer.toString();
}

    public class CustomAdapter extends BaseAdapter {
    private Context mContext;
    Application app;
    private LayoutInflater inflater=null;

    public CustomAdapter(Context c) {
        mContext = c;
         inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }   

    public int getCount() {
        return id.size();
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {

        View vi=convertView;
        if (convertView == null)        
             vi = inflater.inflate(R.layout.list, null);


        TextView txt=(TextView)vi.findViewById(R.id.txtview_id);
        TextView txt1=(TextView)vi.findViewById(R.id.txtview_name);
        TextView txt2=(TextView)vi.findViewById(R.id.txtview_email);
        TextView txt3=(TextView)vi.findViewById(R.id.txtview_address);
        TextView txt4=(TextView)vi.findViewById(R.id.txtview_gender);
        TextView txt5=(TextView)vi.findViewById(R.id.txtview_mobile);
        TextView txt6=(TextView)vi.findViewById(R.id.txtview_home);
        TextView txt7=(TextView)vi.findViewById(R.id.txtview_office);

        txt.setText("Id : " + id.get(position));
        txt1.setText("Name : " + name.get(position));
        txt2.setText("Email : " + email.get(position));
        txt3.setText("Address : " + address.get(position));
        txt4.setText("Gender : " + gender.get(position));
        txt5.setText("Mobile : " + mobile.get(position));
        txt6.setText("Home : " + home.get(position));
        txt7.setText("Office : " + office.get(position));

        return vi;
    };
}
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6364698

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档