android json 解析

xiaoxiao2021-02-28  44

笔者是刚入门的菜鸟,不足之处,请多多指教,谢谢。

笔者的网络请求用的是OKHTTP,JSON解析用的是GSON。

下面是请求成功的返回方法:

@Override public void onResponse(Call call, Response response) throws IOException { // 请求的结果 String result = response.body().string(); // 新建gson Gson gson = new Gson(); JSONObject jsonObject = null; try { // json 格式化 jsonObject = new JSONObject(result); // 这里的返回的是数组格式的json JSONArray jsonArray = jsonObject.getJSONArray("Data"); // 通过循环 取出一个个的 object for(int i = 0; i < jsonArray.length(); i++) { Product product = new Product(); JSONObject object = jsonArray.getJSONObject(i); product.productid = object.getString("productid"); product.productname = object.getString("productname"); product.classid = object.getString("classid"); product.productspec = object.getString("productspec"); product.productpricethis = (float) object.getDouble("productpricethis"); product.productpic = object.getString("productpic"); product.productnumber = object.getString("productnumber"); data.add(product); } handler.sendEmptyMessage(1); } catch (JSONException e) { e.printStackTrace(); } }

上面的方法在object属性少的时候还能接受,但属性多了的话,就比较麻烦了,而且属性的名字也容易搞错,效率不高。

后来上网查了下,原来可以直接传一个bean类过去,直接就能完成属性的赋值,代码如下:

@Override public void onResponse(Call call, Response response) throws IOException { // 请求的结果 String result = response.body().string(); // 新建gson Gson gson = new Gson(); JSONObject jsonObject = null; try { // json 格式化 jsonObject = new JSONObject(result); // 这里的返回的是数组格式的json JSONArray jsonArray = jsonObject.getJSONArray("Data"); // 通过循环 取出一个个的 object for(int i = 0; i < jsonArray.length(); i++) { String objectStr = jsonArray.getString(i); // 解析produc类 Product product = gson.fromJson(objectStr, Product.class); // 添加到数组中 data.add(product); } handler.sendEmptyMessage(1); } catch (JSONException e) { e.printStackTrace(); } }

Product 类的每个属性都要实现各自的get、set方法,属性的类型要和返回的类型一致。

String objectStr = jsonArray.getString(i); // 解析produc类 Product product = gson.fromJson(objectStr, Product.class);

主要是把属性赋值的代码换成上面的两句代码来实现

转载请注明原文地址: https://www.6miu.com/read-600038.html

最新回复(0)