OkHttpClient 通过接口传递参数获取json数据并解析

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_34915398/article/details/81365617

通过接口传递参数,获取json数据(下例仅传一个参数):

1. 添加依赖

implementation 'com.zhy:okhttputils:2.6.2'

2. 网络请求

    /**
     * 开辟子线程进行联网请求获取JSON数据
     * OkHttpClient post方法
     * @return
     */
    private void getDataFromNet() {
        final String URL = Constants.baseUrl+"WebService.asmx/GetTopScenicTicket";
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 1 创建okhttpclient对象
                OkHttpClient okHttpClient = new OkHttpClient();
                RequestBody requestBody = new FormBody.Builder()
                        .add("Number", "1")
                        .build();
                // 2 创建请求方式
                Request request = new Request.Builder()
                        .url(URL)
                        .post(requestBody)
                        .build();
                Response response = null;
                // 3 执行请求操作
                try {
                    response = okHttpClient.newCall(request).execute();
                    //判断请求是否成功
                    if (response.isSuccessful()) {
                        //打印服务端返回结果
                        final String res = response.body().string();
                        //请求成功则解析
                        jsonJXdata(res);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }).start();
    }

(OkhttpClient POST异步请求 封装  请移步 https://blog.csdn.net/qq_34915398/article/details/81448184

3. 解析返回的数据

    /**
     * 解析JSON方法
     * @param res
     */
    private void jsonJXdata(String res) {
        if (res != null) {
            try {
                String jsonStr = res.replace("\"[{", "[{").replace("}]\"", "}]").replace("\\\"", "\"").replace("\\", "");  //替换字符
                System.out.println(jsonStr);
                Object object = new JSONTokener(jsonStr).nextValue();
                if (object instanceof JSONObject) {
                    System.out.println("==我是JSONObject==");
                    JSONObject jsonObject = (JSONObject) object;

                    if (jsonObject.has("id")) {
                        String id = jsonObject.getString("id");

                        if (!TextUtils.isEmpty(id)) {
                            System.out.println("id==" + id);
                        }
                    }
                } else if (object instanceof JSONArray) {
                    System.out.println("==我是JSONArray==");
                    JSONArray jsonArray = (JSONArray) object;

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        //根据项目返回的数据编写
                        if (jsonObject.has("id")) {   
                            String id = jsonObject.getString("id");
                            String scenicName=jsonObject.getString("ScenicName");
                            Double scenicPrice=jsonObject.getDouble("ChildTicketPrice");
                            String scenicLocation=jsonObject.getString("ScenicLoaction");
                            Double scenicScore=jsonObject.getDouble("ScenicScore");
                            String image1 = jsonObject.getString("image1");
                            if (!TextUtils.isEmpty(id)) {
                                Map<String, Object> map = new HashMap<>();
                                map.put("ScenicName", scenicName);
                                map.put("ChildTicketPrice", scenicPrice);
                                map.put("ScenicLoaction", scenicLocation);
                                map.put("ScenicScore", scenicScore);
                                map.put("image1", image1);
                                list.add(map);
                                //打印测试
                                System.out.println("id==" + id+"scenicName=="+scenicName+"scenicPrice=="+scenicPrice+"scenicLocation=="+scenicLocation+"sceincScore=="+scenicScore+"image1=="+image1);
                            }
                        }
                    }
                }
                Message msg=new Message();
                msg.what=1;
                handler.sendMessage(msg);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    public Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    ScenicAdapter scenicAdapter = new ScenicAdapter(ScenicActivity.this, list);   //适配器,提前写好
                    LinearLayoutManager layoutManager = new LinearLayoutManager(ScenicActivity.this);
                    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                    rv_scenic.setLayoutManager(layoutManager); //recycleview 设置布局管理
                    rv_scenic.setAdapter(scenicAdapter);  //设置适配器
                    break;
            }
        }

    };

4. 适配器数据绑定

public class ScenicAdapter extends RecyclerView.Adapter<ScenicAdapter.ViewHolder> {
    private Context mContext;
    List<Map<String,Object>> list;
    public ScenicAdapter(Context mContext, List<Map<String,Object>> list) {
        this.mContext = mContext;
        this.list = list;
    }
    @NonNull
    @Override
    public ScenicAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.scenic_item, parent, false);
        final ViewHolder holder = new ViewHolder(view);
        //设置点击事件
        holder.scenicRcv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = holder.getAdapterPosition();
                Toast.makeText(mContext,"景点"+position, Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(mContext, ScenicInfoActivity.class);
                mContext.startActivity(intent);
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ScenicAdapter.ViewHolder holder, int position) {
       // holder.tv_scenic_name.setText(list.get(position).get("name").toString());
        //根据位置得到相应的数据
        Glide.with(mContext).load(Constants.baseUrl+list.get(position).get("image1")).into(holder.iv_scenic);
        //System.out.println("id==" + list.get(position).get("image1"));
        holder.tv_scenic_name.setText(list.get(position).get("ScenicName").toString());
        holder.tv_scenic_price.setText(list.get(position).get("ChildTicketPrice").toString());
        holder.tv_scenic_location.setText(list.get(position).get("ScenicLoaction").toString());
        holder.tv_scenic_score.setText(list.get(position).get("ScenicScore").toString());
    }

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

    //     自定义的ViewHolder类
    public class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView iv_scenic;
        private TextView tv_scenic_name;
        private TextView tv_scenic_price;
        private TextView tv_scenic_score;
        private TextView tv_scenic_location;
        private View scenicRcv;
        public ViewHolder(View itemView) {
            super(itemView);
            //实例化布局参数
            scenicRcv = itemView;
            iv_scenic = itemView.findViewById(R.id.iv_scenic);
            tv_scenic_name = itemView.findViewById(R.id.tv_scenic_name);
            tv_scenic_price = itemView.findViewById(R.id.tv_scenic_price);
            tv_scenic_score = itemView.findViewById(R.id.tv_scenic_score);
            tv_scenic_location = itemView.findViewById(R.id.tv_scenic_location);
        }
    }
}

 

展开阅读全文

没有更多推荐了,返回首页