android json 解析
2017-09-13 11:41
176 查看
笔者是刚入门的菜鸟,不足之处,请多多指教,谢谢。
笔者的网络请求用的是OKHTTP,JSON解析用的是GSON。
Product 类的每个属性都要实现各自的get、set方法,属性的类型要和返回的类型一致。
笔者的网络请求用的是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);
主要是把属性赋值的代码换成上面的两句代码来实现
相关文章推荐
- Android JSON解析类 - JsonReader
- android关于Gson解析json数据时,如果属性为null会报空指针的问题
- Android---Volley请求天气接口JSON解析
- [Android | 小代码] 天气预报 简易Demo json解析数组+对象 Gson+Volley简单使用
- Android 使用个迭代器解析json
- android json解析及简单例子
- Android Studio Json解析生成对应实体类 插件GsonFormat
- Android JSON解析(JSONObject和JSONArray)
- android 解析json数据格式(整合)
- Android 编程下使用 Google 的 Gson 解析 Json
- Android中使用GSON包解析JSON数据(简单JSON)
- android 解析json
- Android中数据文件解析(Json解析【从服务器端获取数据并且解析,显示在客户端上面】)
- Android 手机卫士--解析json与消息机制发送不同类型消息
- android json解析及简单例子
- android 详细json解析
- Android JSON解析
- Android学习系列(20)--App数据格式之解析Json
- android中三种xml解析及Json解析方法
- android客户端从服务器端获取json数据并解析