针对实体编程

来源:互联网 发布:linux opt目录的作用 编辑:程序博客网 时间:2024/05/20 16:09

在项目中,之前同事Json解析的时候,之前都是这么写的

 try {                JSONArray list = response.getJSONArray("list");                if(list.length() == 0){                    img_nocontent.setVisibility(View.VISIBLE);                }                for (int i = 0; i < list.length(); i++) {                    HospitalInfo info = new HospitalInfo();                    JSONObject data = list.getJSONObject(i);                    info.setName(data.getString("name"));                    info.setHospital_id(data.getString("hospital_id"));                    infolist.add(info);                }            } catch (JSONException e) {                e.printStackTrace();            }

借助SDK提供的工具来完成Json数据的解析:

import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;

这样写没错,而且,有一个便利的地方就是,如果服务器给返回的数据里有个JsonObject少了个数据的话,我们可以用JsonObject的has(“xxx”) 判断是否存在该数据,然后在取数据,一定程度上防止了NullPointerException的发生。

如下写法:

            JSONObject _json = (JSONObject) _jsonArray.get(i);        InteractInfo info = new InteractInfo();        if(_json.has("username"))            info.setUsername(_json.getString("username"));

有很长一段时间,我也是这样来解析Json的。直到我遇到一个特别发杂的json的时候,我才醒过来,这。。。。。。有点。。。。。。

那么有没有简单的写法儿呢?有,我们可以借助Gson来完成这项工作。

下面要描述的就如标题所示——针对实体编程。

在请求数据时,不再关心返回数据是什么内容。将返回数据,统一视作一个实体。借助Android Studio上的插件 GsonFromat将Json数据转为一个实体Entity。然后针对该Entity进行编程。

  1. 在项目的build.gradle 中加入 gson
  2. 借助JsonUtils.java来进行解析Json
  3. 一句代码完成Json解析,不论多么复杂的Json

引入gson

compile files('libs/gson-2.5.jar')

引入JsonUtils

JsonUtils.java 如下所示:

package com.network;import com.google.gson.Gson;import com.google.gson.GsonBuilder;import com.google.gson.JsonElement;import com.google.gson.JsonPrimitive;import com.google.gson.JsonSerializationContext;import com.google.gson.JsonSerializer;import com.wjq.lib.util.L;import java.lang.reflect.Type;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Locale;/** * Json 解析工具类,借助Gson */public class JsonUtils {    private static GsonBuilder gsonb = null;    static {        gsonb = new GsonBuilder();    }    /**     * 这块儿很可能抛异常,在具体调用处处理吧     * <p/>     * 将一个json 字符串解析为 bean 对象     *     * @param jsonString     * @param type     * @param <T>     * @return     */    public static <T> T toBean(String jsonString, Type type) {        // Gson gson = gsonb.create();        final String dateformat = "yyyy-MM-dd HH:mm:ss";        Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Date.class, new JsonSerializer<Date>() {            public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {                SimpleDateFormat format = new SimpleDateFormat(dateformat, Locale.getDefault());                return new JsonPrimitive(format.format(src));            }        }).setDateFormat(dateformat).create();        L.et("gson", "--JsonUtils.toBean--jsonString:" + jsonString);        if (jsonString != null && !jsonString.equals("{}") && !jsonString.equals("[]")) {            return gson.fromJson(jsonString, type);        } else {            return null;        }    }    /**     * 这块儿很可能抛异常,在具体调用处处理吧     *     * 将对象转为json字符串     * @param bean     * @return     * @throws Exception     */    public static String toString(Object bean) throws Exception {        Gson gson = gsonb.create();        return gson.toJson(bean);    }}

在项目中具体使用

            private List<ProjectListEntity> list = null;            .....            try {                list = JsonUtils.toBean(response.toString(),                        new TypeToken<List<ProjectListEntity>>() {                        }.getType());        } catch (Exception e) {             e.printStackTrace();             onLoadFailInfo();        }

这样做的好处:

  1. 节省了很多的时间,因为之前在手动解析那些json的时候,碰到复杂,长传的json是很费时间的;
  2. 还是节省了很多时间,那些实体都可以借助插件来生成,省下了写实体entity的时间;
  3. 省了很多代码,代码量少了很多。

可以从这里下载上文提到的 JsonUtils.java

0 0