您的位置:首页 > 移动开发 > Objective-C

安卓中获取服务端json数据,使用JSONObject解析,并通过ListView显示出来

2019-06-15 18:47 302 查看

这是在浏览器中访问地址,服务器返回的json数据格式

首先创建两个布局文件

1、activity_main.xml中加入ListView控件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
 
    <ListView
        android:id="@+id/lv_contact"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>
2、view_main.xml中为ListvView进行布局,这里面的六个文本就是用来显示json中的数据(依照个人需要布局啦,这个布局文件可以选择性忽略,贴出来为了后面方便看

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
 
    <LinearLayout
        android:id="@+id/llBlno"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="2dip"
        android:layout_marginRight="2dip"
        android:layout_marginTop="2dip"
        android:orientation="vertical">
 
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="2dip"
            android:layout_marginRight="2dip"
            android:layout_marginTop="2dip"
            android:orientation="horizontal">
            <TextView
                android:id="@+id/tvCargono"
                android:layout_width="170dp"
                android:layout_height="20dp"
                android:gravity="left"
                android:text="钢卷号:"
                />
            <TextView
                android:id="@+id/tvVariety"
                android:layout_width="100dp"
                android:layout_height="20dp"
                android:layout_weight="1"
                android:gravity="start"
                android:text="品种:"
                />
        </LinearLayout>
 
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="2dip"
            android:layout_marginRight="2dip"
            android:layout_marginTop="2dip"
            android:orientation="horizontal">
            <TextView
                android:id="@+id/tvMarkno"
                android:layout_width="170dp"
                android:layout_height="20dp"
                android:gravity="left"
                android:text="牌号:"
                />
            <TextView
                android:id="@+id/tvSpec"
                android:layout_width="100dp"
                android:layout_height="20dp"
                android:layout_weight="1"
                android:gravity="start"
                android:text="规格型号:"
                />
        </LinearLayout>
 
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="2dip"
            android:layout_marginRight="2dip"
            android:layout_marginTop="2dip"
            android:orientation="horizontal">
            <TextView
                android:id="@+id/tvKgs"
                android:layout_width="170dp"
                android:layout_height="20dp"
                android:gravity="start"
                android:text="毛重:"
                />
            <TextView
                android:id="@+id/tvNet"
                android:layout_width="100dp"
                android:layout_height="20dp"
                android:layout_weight="1"
                android:gravity="start"
                android:text="净重:"
                />
        </LinearLayout>
 
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="2dip"
            android:layout_marginRight="2dip"
            android:layout_marginTop="4dip"
            android:orientation="vertical">
            <Button
                android:id="@+id/btnFocus"
                android:layout_width="90dp"
                android:layout_height="25dp"
                android:layout_gravity="center"
                android:gravity="center"
                android:layout_marginBottom="2dp"
                android:text="确认"
                android:textSize="11sp"
                android:textColor="#FFFFFF"
                android:background="#22B6ED"
                />
        </LinearLayout>
 
    </LinearLayout>
 
</RelativeLayout>
 

然后在AndroidManifest.xml中添加访问网络权限:   <uses-permission android:name="android.permission.INTERNET" />

 

接下来就是在MainActivity中获取、解析数据了

我有使用到okHttp,所以需要先导入jar包,在你的AndroidStudio中打开 File下的ProjectStructure

直接输入okHttp搜索

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
 
import org.json.JSONArray;
import org.json.JSONObject;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
 
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 
    public ListView lv;
    public ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    private Context context;
 
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }
 
    private Mybaseadapter list_item;
 
    private void init() {
        list.clear();
        lv = (ListView) findViewById(R.id.lv_contact);
        list_item = new Mybaseadapter();
        lv.setAdapter(list_item);
 
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    //服务端访问地址
                    Request request = new Request
                            .Builder()
                            .url("http://120.36.153.174:9080/CargolistApi/select").build();
                    Response response = client.newCall(request).execute();
                    //得到服务器返回的数据后,调用parseJSONWithJSONObject进行解析
                    String responseData = response.body().string();
                    parseJSONWithJSONObject(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
 
    private void parseJSONWithJSONObject(String jsonData) {
        if (jsonData != null) {
            try {
                JSONObject jsonObject = new JSONObject(jsonData);
 
                //获取数据中的code值,如果是0则正确
                String resultCode = jsonObject.getString("code");
                if (resultCode.equals("0")) {
                    //获取到json数据中里的data内容
                    JSONArray resultJsonArray = jsonObject.getJSONArray("data");
                    Log.d("MainActivity", "data+++" + resultJsonArray);
                    for (int i = 0; i < resultJsonArray.length(); i++) {
                        //循环遍历,获取json数据中data数组里的内容
                        JSONObject Object = resultJsonArray.getJSONObject(i);
                        Map<String, Object> map = new HashMap<String, Object>();
                        try {
                            String cargono = Object.getString("cargono");
                            String variety = Object.getString("variety");
                            String markno = Object.getString("markno");
                            String spec = Object.getString("spec");
                            String kgs = Object.getString("kgs");
                            String net = Object.getString("net");
                    
                            map.put("cargono", cargono);
                            map.put("variety", variety);
                            map.put("markno", markno);
                            map.put("spec", spec);
                            map.put("kgs", kgs);
                            map.put("net", net);
 
                            //保存到ArrayList集合中
                            list.add(map);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
 
                    handler.sendEmptyMessageDelayed(1, 100);
 
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
 
    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {
 
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    list_item.notifyDataSetChanged();
                    break;
            }
        }
    };
 
     
    //listview适配器
    public class Mybaseadapter extends BaseAdapter {
 
        @Override
        public int getCount() {
            return list.size();
        }
 
        @Override
        public Object getItem(int position) {
            return list.get(position);
        }
 
        @Override
        public long getItemId(int position) {
            return position;
        }
 
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
 
            ViewHolder viewHolder = new ViewHolder();
 
            if (convertView == null) {        
                convertView = getLayoutInflater().inflate(R.layout.view_main,null);
                viewHolder.Cargono = (TextView) convertView.findViewById(R.id.tvCargono);
                viewHolder.Variety = (TextView) convertView.findViewById(R.id.tvVariety);
                viewHolder.Markno = (TextView) convertView.findViewById(R.id.tvMarkno);
                viewHolder.Spec = (TextView) convertView.findViewById(R.id.tvSpec);
                viewHolder.Kgs = (TextView) convertView.findViewById(R.id.tvKgs);
                viewHolder.Net = (TextView) convertView.findViewById(R.id.tvNet);
 
                convertView.setTag(viewHolder);
 
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
 
            viewHolder.Cargono.setText("钢卷号:"+list.get(position).get("cargono").toString());
            viewHolder.Variety.setText("品种:"+list.get(position).get("variety").toString());
            viewHolder.Markno.setText("牌号:"+list.get(position).get("markno").toString());
            viewHolder.Spec.setText("规格型号:"+list.get(position).get("spec").toString());
            viewHolder.Kgs.setText("毛重:"+list.get(position).get("kgs").toString());
            viewHolder.Net.setText("净重:"+list.get(position).get("net").toString());
 
            return convertView;
        }
    }
 
    final static class ViewHolder {
        TextView Cargono;
        TextView Variety;
        TextView Markno;
        TextView Spec;
        TextView Kgs;
        TextView Net;
    }
 
    @Override
    public void onClick(View view) {
 
    }
}
 

运行成功的效果图

(遇到问题果然还是论坛提问更有效,感谢评论帮我修改错误的好心人)

 

解析JSON数据还有一种方法是使用谷歌提供的GSON开源库来进行,

GSON库可以将一段JSON格式的字符串自动映射成为一个对象,不需要再手动编写代码进行解析。

 

原文:https://blog.csdn.net/Znnnnnnnn/article/details/89356803

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐