当前位置: 移动技术网 > IT编程>开发语言>Java > Java实现操作JSON的便捷工具类完整实例【重写Google的Gson】

Java实现操作JSON的便捷工具类完整实例【重写Google的Gson】

2019年07月19日  | 移动技术网IT编程  | 我要评论
本文实例讲述了java实现操作json的便捷工具类。分享给大家供大家参考,具体如下: 对于json数据格式的处理,自开发java以来,已用过多种json的开源工具,用得最

本文实例讲述了java实现操作json的便捷工具类。分享给大家供大家参考,具体如下:

对于json数据格式的处理,自开发java以来,已用过多种json的开源工具,用得最好,也用得最high的恐怕要属google的gson了。

特别为它写了一个工具类,放入常备工具中,方便使用。下面是为gson 1.5版本重写的工具类。

依赖包:

slf4j-api-1.6.0.jar
slf4j-log4j12-1.6.0.jar
log4j-1.2.15.jar
gson-1.5.jar

/**
 * copyright 2010 fuchun.
 *
 * licensed under the apache license, version 2.0 (the "license");
 * you may not use this file except in compliance with the license.
 * you may obtain a copy of the license at
 *   http://www.apache.org/licenses/license-2.0
 *
 * unless required by applicable law or agreed to in writing, software
 * distributed under the license is distributed on an "as is" basis,
 * without warranties or conditions of any kind, either express or implied.
 * see the license for the specific language governing permissions and
 * limitations under the license.
 */
package my.tools;
import java.lang.reflect.type;
import java.util.collection;
import java.util.enumeration;
import java.util.iterator;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import com.google.gson.gson;
import com.google.gson.gsonbuilder;
import com.google.gson.reflect.typetoken;
import org.apache.commons.lang.stringutils;
/**
 * 包含操作 {@code json} 数据的常用方法的工具类。
 * <p />
 * 该工具类使用的 {@code json} 转换引擎是 <a href="http://code.google.com/p/google-gson/" rel="external nofollow" rel="external nofollow" mce_href="http://code.google.com/p/google-gson/" rel="external nofollow" rel="external nofollow" target="_blank">
 * {@code google gson}</a>。 下面是工具类的使用案例:
 *
 * <pre>
 * public class user {
 *   @serializedname("pwd")
 *   private string password;
 *   @expose
 *   @serializedname("uname")
 *   private string username;
 *   @expose
 *   @since(1.1)
 *   private string gender;
 *   @expose
 *   @since(1.0)
 *   private string sex;
 *
 *   public user() {}
 *   public user(string username, string password, string gender) {
 *     // user constructor code... ... ...
 *   }
 *
 *   public string getusername()
 *   ... ... ...
 * }
 * list<user> userlist = new linkedlist<user>();
 * user jack = new user("jack", "123456", "male");
 * user marry = new user("marry", "888888", "female");
 * userlist.add(jack);
 * userlist.add(marry);
 * type targettype = new typetoken<list<user>>(){}.gettype();
 * string suserlist1 = jsonutils.tojson(userlist, targettype);
 * suserlist1 ----> [{"uname":"jack","gender":"male","sex":"male"},{"uname":"marry","gender":"female","sex":"female"}]
 * string suserlist2 = jsonutils.tojson(userlist, targettype, false);
 * suserlist2 ----> [{"uname":"jack","pwd":"123456","gender":"male","sex":"male"},{"uname":"marry","pwd":"888888","gender":"female","sex":"female"}]
 * string suserlist3 = jsonutils.tojson(userlist, targettype, 1.0d, true);
 * suserlist3 ----> [{"uname":"jack","sex":"male"},{"uname":"marry","sex":"female"}]
 * </pre>
 *
 * @author fuchun
 * @since ay-commons-lang 1.0
 * @version 1.1.0
 */
public class jsonutils {
  private static final logger logger = loggerfactory.getlogger(jsonutils.class);
  /** 空的 {@code json} 数据 - <code>"{}"</code>。 */
  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} 的 <code>@since</code> 注解常用的版本号常量 - {@code 1.0}。 */
  public static final double since_version_10 = 1.0d;
  /** {@code google gson} 的 <code>@since</code> 注解常用的版本号常量 - {@code 1.1}。 */
  public static final double since_version_11 = 1.1d;
  /** {@code google gson} 的 <code>@since</code> 注解常用的版本号常量 - {@code 1.2}。 */
  public static final double since_version_12 = 1.2d;
  /** {@code google gson} 的 <code>@until</code> 注解常用的版本号常量 - {@code 1.0}。 */
  public static final double until_version_10 = since_version_10;
  /** {@code google gson} 的 <code>@until</code> 注解常用的版本号常量 - {@code 1.1}。 */
  public static final double until_version_11 = since_version_11;
  /** {@code google gson} 的 <code>@until</code> 注解常用的版本号常量 - {@code 1.2}。 */
  public static final double until_version_12 = since_version_12;
  /**
   * <p>
   * <code>jsonutils</code> instances should not be constructed in standard programming. instead,
   * the class should be used as <code>jsonutils.fromjson("foo");</code>.
   * </p>
   * <p>
   * this constructor is public to permit tools that require a javabean instance to operate.
   * </p>
   */
  public jsonutils() {
    super();
  }
  /**
   * 将给定的目标对象根据指定的条件参数转换成 {@code json} 格式的字符串。
   * <p />
   * <strong>该方法转换发生错误时,不会抛出任何异常。若发生错误时,曾通对象返回 <code>"{}"</code>; 集合或数组对象返回 <code>"[]"</code>
   * </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 (stringutils.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, false, null, null, true);
  }
  /**
   * 将给定的目标对象转换成 {@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 (stringutils.isblank(json)) {
      return null;
    }
    gsonbuilder builder = new gsonbuilder();
    if (stringutils.isblank(datepattern)) {
      datepattern = default_date_pattern;
    }
    gson gson = builder.create();
    try {
      return gson.fromjson(json, token.gettype());
    } catch (exception ex) {
      logger.error(json + " 无法转换为 " + token.getrawtype().getname() + " 对象!", ex);
      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 (stringutils.isblank(json)) {
      return null;
    }
    gsonbuilder builder = new gsonbuilder();
    if (stringutils.isblank(datepattern)) {
      datepattern = default_date_pattern;
    }
    gson gson = builder.create();
    try {
      return gson.fromjson(json, clazz);
    } catch (exception ex) {
      logger.error(json + " 无法转换为 " + clazz.getname() + " 对象!", ex);
      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} 对象返回 <code>"{}"</code>; 集合或数组对象返回
   * <code>"[]"</code>。 其本基本类型,返回相应的基本值。
   *
   * @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) {
      logger.warn("目标对象 " + target.getclass().getname() + " 转换 json 字符串时,发生异常!", ex);
      if (target instanceof collection<?> || target instanceof iterator<?> || target instanceof enumeration<?>
          || target.getclass().isarray()) {
        result = empty_json_array;
      }
    }
    return result;
  }
}

ps:关于json操作,这里再为大家推荐几款比较实用的json在线工具供大家参考使用:

在线json代码检验、检验、美化、格式化工具:

json在线格式化工具:

在线xml/json互相转换工具:

json代码在线格式化/美化/压缩/编辑/转换工具:

在线json压缩/转义工具:

更多关于java相关内容感兴趣的读者可查看本站专题:《java操作json格式数据技巧总结》、《java数组操作技巧总结》、《java字符与字符串操作技巧总结》、《java数学运算技巧总结》、《java数据结构与算法教程》及《java操作dom节点技巧总结

希望本文所述对大家java程序设计有所帮助。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网