开发中我们常常需要在页面之间进行传值,今天讲下用json传值,
简单点讲json传值即把对象转成字符串传递接收后再解析成对象,
网上那些解析方法都是很繁琐不适合日常开发,我们可以直接用
Google 的gson
工欲善其事必先利其器,我们先先依赖GSON
下载gson jar包或者直接依赖
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>
2.8
.0
</version>
</dependency>
底下是一个对gson封装的utils,直接cv到你的代码即可。
** * 包含操作 {@code JSON} 数据的常用方法的工具类。 * <p /> * 该工具类使用的 {@code JSON} 转换引擎是 {@code Google Gson}</a>。 下面是工具类的使用案例: //解析json数组 * JSONUtils.fromJson(content, new TypeToken<ListVO<Config>>() {}); //解析json对象 * JSONUtils.fromJson(content, new TypeToken<Result>() {}); */ public class JSONUtils { /** * 空的 {@code JSON} 数据 - * * <pre> * "{}" * </pre> * * 。 */ public static final String EMPTY_JSON = "{}"; /** 空的 {@code JSON} 数组(集合)数据 - {@code "[]"}。 */ public static final String EMPTY_JSON_ARRAY = "[]"; /** 默认的 {@code JSON} 日期/时间字段的格式化模式。 */ public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss SSS"; /** * {@code Google Gson} 的 * * <pre> * @Since * </pre> * * 注解常用的版本号常量 - {@code 1.0}。 */ public static final double SINCE_VERSION_10 = 1.0d; /** * {@code Google Gson} 的 * * <pre> * @Since * </pre> * * 注解常用的版本号常量 - {@code 1.1}。 */ public static final double SINCE_VERSION_11 = 1.1d; /** * {@code Google Gson} 的 * * <pre> * @Since * </pre> * * 注解常用的版本号常量 - {@code 1.2}。 */ public static final double SINCE_VERSION_12 = 1.2d; /** * {@code Google Gson} 的 * * <pre> * @Until * </pre> * * 注解常用的版本号常量 - {@code 1.0}。 */ public static final double UNTIL_VERSION_10 = SINCE_VERSION_10; /** * {@code Google Gson} 的 * * <pre> * @Until * </pre> * * 注解常用的版本号常量 - {@code 1.1}。 */ public static final double UNTIL_VERSION_11 = SINCE_VERSION_11; /** * {@code Google Gson} 的 * * <pre> * @Until * </pre> * * 注解常用的版本号常量 - {@code 1.2}。 */ public static final double UNTIL_VERSION_12 = SINCE_VERSION_12; /** * <p> * * <pre> * JSONUtils * </pre> * * instances should NOT be constructed in standard programming. Instead, the * class should be used as * * <pre> * JSONUtils.fromJson("foo"); * </pre> * * . * </p> * <p> * This constructor is public to permit tools that require a JavaBean * instance to operate. * </p> */ public JSONUtils() { super(); } /** * 将给定的目标对象根据指定的条件参数转换成 {@code JSON} 格式的字符串。 * <p /> * <strong>该方法转换发生错误时,不会抛出任何异常。若发生错误时,曾通对象返回 * * <pre> * "{}" * </pre> * * ; 集合或数组对象返回 * * <pre> * "[]" * </pre> * * </strong> * * @param target * 目标对象。 * @param targetType * 目标对象的类型。 * @param isSerializeNulls * 是否序列化 {@code null} 值字段。 * @param version * 字段的版本号注解。 * @param datePattern * 日期字段的格式化模式。 * @param excludesFieldsWithoutExpose * 是否排除未标注 {@literal @Expose} 注解的字段。 * @return 目标对象的 {@code JSON} 格式的字符串。 * @since 1.0 */ public static String toJson(Object target, Type targetType, boolean isSerializeNulls, Double version, String datePattern, boolean excludesFieldsWithoutExpose) { if (target == null) return EMPTY_JSON; GsonBuilder builder = new GsonBuilder(); if (isSerializeNulls) builder.serializeNulls(); if (version != null) builder.setVersion(version.doubleValue()); if (isBlank(datePattern)) datePattern = DEFAULT_DATE_PATTERN; builder.setDateFormat(datePattern); if (excludesFieldsWithoutExpose) builder.excludeFieldsWithoutExposeAnnotation(); return toJson(target, targetType, builder); } /** * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法只用来转换普通的 {@code JavaBean} * 对象。</strong> * <ul> * <li>该方法只会转换标有 {@literal @Expose} 注解的字段;</li> * <li>该方法不会转换 {@code null} 值字段;</li> * <li>该方法会转换所有未标注或已标注 {@literal @Since} 的字段;</li> * <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss SSS};</li> * </ul> * * @param target * 要转换成 {@code JSON} 的目标对象。 * @return 目标对象的 {@code JSON} 格式的字符串。 * @since 1.0 */ public static String toJson(Object target) { return toJson(target, null, true, null, null, false); } /** * protect 修饰的字段过滤掉 * @param target * @return */ public static String toJsonWithoutProtected(Object target) { if (target == null) return EMPTY_JSON; GsonBuilder builder = new GsonBuilder(); builder.serializeNulls(); builder.excludeFieldsWithModifiers(Modifier.PROTECTED); return toJson(target, null, builder); } /** * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法只用来转换普通的 {@code JavaBean} * 对象。</strong> * <ul> * <li>该方法只会转换标有 {@literal @Expose} 注解的字段;</li> * <li>该方法不会转换 {@code null} 值字段;</li> * <li>该方法会转换所有未标注或已标注 {@literal @Since} 的字段;</li> * </ul> * * @param target * 要转换成 {@code JSON} 的目标对象。 * @param datePattern * 日期字段的格式化模式。 * @return 目标对象的 {@code JSON} 格式的字符串。 * @since 1.0 */ public static String toJson(Object target, String datePattern) { return toJson(target, null, false, null, datePattern, true); } /** * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法只用来转换普通的 {@code JavaBean} * 对象。</strong> * <ul> * <li>该方法只会转换标有 {@literal @Expose} 注解的字段;</li> * <li>该方法不会转换 {@code null} 值字段;</li> * <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss SSS};</li> * </ul> * * @param target * 要转换成 {@code JSON} 的目标对象。 * @param version * 字段的版本号注解({@literal @Since})。 * @return 目标对象的 {@code JSON} 格式的字符串。 * @since 1.0 */ public static String toJson(Object target, Double version) { return toJson(target, null, false, version, null, true); } /** * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法只用来转换普通的 {@code JavaBean} * 对象。</strong> * <ul> * <li>该方法不会转换 {@code null} 值字段;</li> * <li>该方法会转换所有未标注或已标注 {@literal @Since} 的字段;</li> * <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss SSS};</li> * </ul> * * @param target * 要转换成 {@code JSON} 的目标对象。 * @param excludesFieldsWithoutExpose * 是否排除未标注 {@literal @Expose} 注解的字段。 * @return 目标对象的 {@code JSON} 格式的字符串。 * @since 1.0 */ public static String toJson(Object target, boolean excludesFieldsWithoutExpose) { return toJson(target, null, false, null, null, excludesFieldsWithoutExpose); } /** * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法只用来转换普通的 {@code JavaBean} * 对象。</strong> * <ul> * <li>该方法不会转换 {@code null} 值字段;</li> * <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss SSS};</li> * </ul> * * @param target * 要转换成 {@code JSON} 的目标对象。 * @param version * 字段的版本号注解({@literal @Since})。 * @param excludesFieldsWithoutExpose * 是否排除未标注 {@literal @Expose} 注解的字段。 * @return 目标对象的 {@code JSON} 格式的字符串。 * @since 1.0 */ public static String toJson(Object target, Double version, boolean excludesFieldsWithoutExpose) { return toJson(target, null, false, version, null, excludesFieldsWithoutExpose); } /** * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法通常用来转换使用泛型的对象。</strong> * <ul> * <li>该方法只会转换标有 {@literal @Expose} 注解的字段;</li> * <li>该方法不会转换 {@code null} 值字段;</li> * <li>该方法会转换所有未标注或已标注 {@literal @Since} 的字段;</li> * <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss SSSS};</li> * </ul> * * @param target * 要转换成 {@code JSON} 的目标对象。 * @param targetType * 目标对象的类型。 * @return 目标对象的 {@code JSON} 格式的字符串。 * @since 1.0 */ public static String toJson(Object target, Type targetType) { return toJson(target, targetType, false, null, null, true); } /** * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法通常用来转换使用泛型的对象。</strong> * <ul> * <li>该方法只会转换标有 {@literal @Expose} 注解的字段;</li> * <li>该方法不会转换 {@code null} 值字段;</li> * <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss SSSS};</li> * </ul> * * @param target * 要转换成 {@code JSON} 的目标对象。 * @param targetType * 目标对象的类型。 * @param version * 字段的版本号注解({@literal @Since})。 * @return 目标对象的 {@code JSON} 格式的字符串。 * @since 1.0 */ public static String toJson(Object target, Type targetType, Double version) { return toJson(target, targetType, false, version, null, true); } /** * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法通常用来转换使用泛型的对象。</strong> * <ul> * <li>该方法不会转换 {@code null} 值字段;</li> * <li>该方法会转换所有未标注或已标注 {@literal @Since} 的字段;</li> * <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss SSS};</li> * </ul> * * @param target * 要转换成 {@code JSON} 的目标对象。 * @param targetType * 目标对象的类型。 * @param excludesFieldsWithoutExpose * 是否排除未标注 {@literal @Expose} 注解的字段。 * @return 目标对象的 {@code JSON} 格式的字符串。 * @since 1.0 */ public static String toJson(Object target, Type targetType, boolean excludesFieldsWithoutExpose) { return toJson(target, targetType, false, null, null, excludesFieldsWithoutExpose); } /** * 将给定的目标对象转换成 {@code JSON} 格式的字符串。<strong>此方法通常用来转换使用泛型的对象。</strong> * <ul> * <li>该方法不会转换 {@code null} 值字段;</li> * <li>该方法转换时使用默认的 日期/时间 格式化模式 - {@code yyyy-MM-dd HH:mm:ss SSS};</li> * </ul> * * @param target * 要转换成 {@code JSON} 的目标对象。 * @param targetType * 目标对象的类型。 * @param version * 字段的版本号注解({@literal @Since})。 * @param excludesFieldsWithoutExpose * 是否排除未标注 {@literal @Expose} 注解的字段。 * @return 目标对象的 {@code JSON} 格式的字符串。 * @since 1.0 */ public static String toJson(Object target, Type targetType, Double version, boolean excludesFieldsWithoutExpose) { return toJson(target, targetType, false, version, null, excludesFieldsWithoutExpose); } /** * 将给定的 {@code JSON} 字符串转换成指定的类型对象。 * * @param <T> * 要转换的目标类型。 * @param json * 给定的 {@code JSON} 字符串。 * @param token * {@code com.google.gson.reflect.TypeToken} 的类型指示类对象。 * @param datePattern * 日期格式模式。 * @return 给定的 {@code JSON} 字符串表示的指定的类型对象。 * @since 1.0 */ public static <T> T fromJson(String json, TypeToken<T> token, String datePattern) { if (isBlank(json)) { return null; } GsonBuilder builder = new GsonBuilder(); if (isBlank(datePattern)) { datePattern = DEFAULT_DATE_PATTERN; } Gson gson = builder.create(); try { return gson.fromJson(json, token.getType()); } catch (Exception ex) { ex.printStackTrace(); Log.e(/*json + */" 无法转换为 " + token.getRawType().getName() + " 对象!", ex.getMessage()); return null; } } /** * 将给定的 {@code JSON} 字符串转换成指定的类型对象。 * * @param <T> * 要转换的目标类型。 * @param json * 给定的 {@code JSON} 字符串。 * @param token * {@code com.google.gson.reflect.TypeToken} 的类型指示类对象。 * @return 给定的 {@code JSON} 字符串表示的指定的类型对象。 * @since 1.0 */ public static <T> T fromJson(String json, TypeToken<T> token) { return fromJson(json, token, null); } /** * 将给定的 {@code JSON} 字符串转换成指定的类型对象。<strong>此方法通常用来转换普通的 {@code JavaBean} * 对象。</strong> * * @param <T> * 要转换的目标类型。 * @param json * 给定的 {@code JSON} 字符串。 * @param clazz * 要转换的目标类。 * @param datePattern * 日期格式模式。 * @return 给定的 {@code JSON} 字符串表示的指定的类型对象。 * @since 1.0 */ public static <T> T fromJson(String json, Class<T> clazz, String datePattern) { if (isBlank(json)) { return null; } GsonBuilder builder = new GsonBuilder(); if (isBlank(datePattern)) { datePattern = DEFAULT_DATE_PATTERN; } Gson gson = builder.create(); try { return gson.fromJson(json, clazz); } catch (Exception ex) { Log.e(json + " 无法转换为 " + clazz.getName() + " 对象!", ex.getMessage()); return null; } } /** * 将给定的 {@code JSON} 字符串转换成指定的类型对象。<strong>此方法通常用来转换普通的 {@code JavaBean} * 对象。</strong> * * @param <T> * 要转换的目标类型。 * @param json * 给定的 {@code JSON} 字符串。 * @param clazz * 要转换的目标类。 * @return 给定的 {@code JSON} 字符串表示的指定的类型对象。 * @since 1.0 */ public static <T> T fromJson(String json, Class<T> clazz) { return fromJson(json, clazz, null); } /** * 将给定的目标对象根据{@code GsonBuilder} 所指定的条件参数转换成 {@code JSON} 格式的字符串。 * <p /> * 该方法转换发生错误时,不会抛出任何异常。若发生错误时,{@code JavaBean} 对象返回 * * <pre> * "{}" * </pre> * * ; 集合或数组对象返回 * * <pre> * "[]" * </pre> * * 。 其本基本类型,返回相应的基本值。 * * @param target * 目标对象。 * @param targetType * 目标对象的类型。 * @param builder * 可定制的{@code Gson} 构建器。 * @return 目标对象的 {@code JSON} 格式的字符串。 * @since 1.1 */ public static String toJson(Object target, Type targetType, GsonBuilder builder) { if (target == null) return EMPTY_JSON; Gson gson = null; if (builder == null) { gson = new Gson(); } else { gson = builder.create(); } String result = EMPTY_JSON; try { if (targetType == null) { result = gson.toJson(target); } else { result = gson.toJson(target, targetType); } } catch (Exception ex) { Log.w("目标对象 " + target.getClass().getName() + " 转换 JSON 字符串时,发生异常!", ex.getMessage()); if (target instanceof Collection<?> || target instanceof Iterator<?> || target instanceof Enumeration<?> || target.getClass().isArray()) { result = EMPTY_JSON_ARRAY; } } return result; } private static boolean isBlank(String text) { return null == text || "".equals(text.trim()); } public static String simpleObjectToJsonStr(Object obj,List<Class> claList) throws IllegalArgumentException, IllegalAccessException{ if(obj==null){ return "null"; } String jsonStr = "{"; Class<?> cla = obj.getClass(); Field fields[] = cla.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); if(field.getType() == long.class){ jsonStr += "\""+field.getName()+"\":"+field.getLong(obj)+","; }else if(field.getType() == double.class){ jsonStr += "\""+field.getName()+"\":"+field.getDouble(obj)+","; }else if(field.getType() == float.class){ jsonStr += "\""+field.getName()+"\":"+field.getFloat(obj)+","; }else if(field.getType() == int.class){ jsonStr += "\""+field.getName()+"\":"+field.getInt(obj)+","; }else if(field.getType() == boolean.class){ jsonStr += "\""+field.getName()+"\":"+field.getBoolean(obj)+","; }else if(field.getType() == Integer.class||field.getType() == Boolean.class ||field.getType() == Double.class||field.getType() == Float.class ||field.getType() == Long.class){ jsonStr += "\""+field.getName()+"\":"+field.get(obj)+","; }else if(field.getType() == String.class){ jsonStr += "\""+field.getName()+"\":\""+field.get(obj)+"\","; }else if(field.getType().toString().endsWith("List")){ String value = simpleListToJsonStr((List<?>)field.get(obj),claList); jsonStr += "\""+field.getName()+"\":"+value+","; }else{ if(claList!=null&&claList.size()!=0&&claList.contains(field.getType())){ String value = simpleObjectToJsonStr(field.get(obj),claList); jsonStr += "\""+field.getName()+"\":"+value+","; }else{ jsonStr += "\""+field.getName()+"\":null,"; } } } jsonStr = jsonStr.substring(0,jsonStr.length()-1); jsonStr += "}"; return jsonStr; } public static String simpleListToJsonStr(List<?> list,List<Class> claList) throws IllegalArgumentException, IllegalAccessException{ if(list==null||list.size()==0){ return "[]"; } String jsonStr = "["; for (Object object : list) { jsonStr += simpleObjectToJsonStr(object,claList)+","; } jsonStr = jsonStr.substring(0,jsonStr.length()-1); jsonStr += "]"; return jsonStr; } }
然后就可以使用了,
1 对于集合
系列化
List<Bean> datas = generateData(); String str = JSONUtils.toJson(datas);
接收解析
List<FullCutGroup> prodInfoVOs = JSONUtils.fromJson(str, new TypeToken<List<Bean>>() {});2对于对象系列化String str = JSONUtils.toJson(Bean);
接收解析是不是非常方便简单,有任何疑问或建议欢迎评论私信Bean bean= JSONUtils.fromJson(str,Bean.class);