Android(安卓)之gson字符串转java bean
16lz
2021-01-26
import com.google.gson.Gson;import com.google.gson.JsonNull;import com.google.gson.JsonSyntaxException;import org.codehaus.jackson.map.ObjectMapper;import org.json.JSONObject;import java.lang.reflect.Type;public class JsonUtils { // 定义jackson对象 private static final ObjectMapper MAPPER = new ObjectMapper(); // 采取单例模式 private static Gson gson = new Gson(); private JsonUtils() { } /** * @param src :将要被转化的对象 * @return :转化后的JSON串 * @MethodName : toJson * @Description : 将对象转为JSON串,此方法能够满足大部分需求 */ public static String toJson(Object src) { if (null == src) { return gson.toJson(JsonNull.INSTANCE); } try { return gson.toJson(src); } catch (JsonSyntaxException e) { e.printStackTrace(); } return null; } /** * @param json * @param classOfT * @return * @MethodName : fromJson * @Description : 用来将JSON串转为对象,但此方法不可用来转带泛型的集合 */ public static Object fromJson(String json, Class classOfT) { try { return gson.fromJson(json, (Type) classOfT); } catch (JsonSyntaxException e) { System.out.println(e.toString() + "------------------------------"); e.printStackTrace(); } return null; } /** * 将json结果集转化为对象 * * @param jsonData json数据 * @param beanType * @param 对象中的object类型 * @return */ public static T jsonToPojo(String jsonData, Class beanType) { try { T t = MAPPER.readValue(jsonData, beanType); return t; } catch (Exception e) { System.out.println(e.toString() + "------------------------------"); e.printStackTrace(); } return null; } /** * @param json * @param typeOfT * @return * @MethodName : fromJson * @Description : 用来将JSON串转为对象,此方法可用来转带泛型的集合,如:Type为 new * TypeToken>(){}.getType() * ,其它类也可以用此方法调用,就是将List替换为你想要转成的类 */ public static Object fromJson(String json, Type typeOfT) { try { return gson.fromJson(json, typeOfT); } catch (JsonSyntaxException e) { e.printStackTrace(); } return null; } /** * 获取json中的某个值 * * @param json * @param key * @return */ public static String getValue(String json, String key) { try { JSONObject object = new JSONObject(json); return object.getString(key); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 获取json中的list值 * * @param json * @return */ public static String getListValue(String json) { try { JSONObject object = new JSONObject(json); return object.getString("list"); } catch (Exception e) { e.printStackTrace(); } return null; } public static Double getDoubleValue(String json, String key) { try { JSONObject object = new JSONObject(json); return object.getDouble(key); } catch (Exception e) { e.printStackTrace(); } return null; } public static int getIntValue(String json, String key) { try { JSONObject object = new JSONObject(json); return object.getInt(key); } catch (Exception e) { e.printStackTrace(); } return 0; }}
更多相关文章
- 开源库
- Android(安卓)网络状态操作
- 使用Intent实现页面跳转 (另一种方法)
- android JS互交图片点击事件
- Android(安卓)LayoutInflater详解
- listview使用BaseAdapter显示图片和文字
- Android连按两次back键退出APP
- Android在SurfaceView做动画一般方法
- android-async-http