import android.text.TextUtils;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 基于Gson进行解析
*
* @author Administrator
*/
public class JsonUtil {
private static Gson gson;
/***
* 创建一个gson对象
*/
public static Gson creat() {
if (gson == null) {
gson = new Gson();
}
return gson;
}
/**
* 把一个bean变成json字符串
*
* @param bean
* @return
*/
public static String parseBeanToJson(Object bean) {
try {
return creat().toJson(bean);
} catch (Exception e) {
}
return null;
}
/**
* 把一个map变成json字符串
*
* @param map
* @return
*/
public static String parseMapToJson(Map<?, ?> map) {
try {
return creat().toJson(map);
} catch (Exception e) {
}
return null;
}
/**
* 把一个json字符串变成对象
*
* @param json
* @param type
* @return
*/
public static <T> T parseJsonToBean(String json, Type type) {
// L.e("json数据", json);
T t = null;
// json.replaceAll("\\\\","");
try {
t = creat().fromJson(json, type);
} catch (Exception e) {
L.e("JsonUtil", "解析json数据时出现异常\njson = " + json );
L.e("JsonUtil", "解析json数据时出现异常\njson = " + e );
}
return t;
}
/**
* 把json字符串变成map
*
* @param json
* @return
*/
public static HashMap<String, Object> parseJsonToMap(String json) {
Type type = new TypeToken<HashMap<String, Object>>() {
}.getType();
HashMap<String, Object> map = null;
try {
map = creat().fromJson(json, type);
} catch (Exception e) {
L.e("JsonUtil", "解析json数据时出现异常\njson = " + json);
}
return map;
}
/**
* 把json字符串变成集合
* params: new TypeToken<List<yourbean>>(){}.getType(),
*
* @param json
* @param type new TypeToken<List<yourbean>>(){}.getType()
* @return
*/
public static List<?> parseJsonToList(String json, Type type) {
List<?> list = creat().fromJson(json, type);
return list;
}
}
JsonUtils代码记录保存
最新推荐文章于 2025-05-26 15:25:32 发布