JsonUtil工具类的封装

来源:互联网 发布:淘宝买塑料枪 编辑:程序博客网 时间:2024/06/07 02:51

首先在app/build.gradle文件中添加依赖:

compile 'com.google.code.gson:gson:2.8.0'//Gson依赖注入
import android.text.TextUtils;import com.google.gson.Gson;import org.json.JSONException;import org.json.JSONObject;import java.util.Iterator;import java.util.Map;/** * Created by Administrator on 2016/11/29. */public class JsonUtil {    //json转换成bean类    public static <T> T jsonString2Obj(String json, Class<T> clazz) {        if (TextUtils.isEmpty(json) || clazz == null) {            return null;        }        return new Gson().fromJson(json, clazz);    }    //bean类转换成json字符串    public static String obj2JsonString(Object obj) {        if (obj == null) {            return null;        }        return new Gson().toJson(obj);    }    //map集合转换成json字符串    public static String map2JsonString(Map<String, Object> map) throws JSONException {        if (map == null || map.size() == 0) {            return null;        }        Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();        JSONObject jsonObject = new JSONObject();        while (iterator.hasNext()) {            Map.Entry<String, Object> mapNext = iterator.next();            jsonObject.put(mapNext.getKey(), mapNext.getValue());        }        if (jsonObject != null) {            return jsonObject.toString();        } else {            return null;        }    }}


1 0
原创粉丝点击