• 使用jackson对Java对象与JSON字符串相互转换的一些总结


    本文为菠萝大象原创,如要转载请注明出处。http://www.blogjava.net/bolo

    代码无真相,为了最简单的说明,我直接上代码。

    public class User {

        private String name;

        private Gender gender;

        private List<Account> accounts;

        省略get和set方法

    ...

    }

    public enum Gender {

        MALE,

        FEMALE

    }

    public class Account {

        private Integer id;

        private String cardId;

        private BigDecimal balance;

     private Date date;

     省略get和set方法

    ...

    }

    public static void main(String[] args) throws Exception {

           User user = new User();

           user.setName("菠萝大象");

           user.setGender(Gender.MALE);

           List<Account> accounts = new ArrayList<Account>();

           Account account = new Account();

           account.setId(1);

           account.setBalance(BigDecimal.valueOf(1900.2));

           account.setCardId("423335533434");

           account.setDate(new Date());

           accounts.add(account);

           account = new Account();

           account.setId(2);

           account.setBalance(BigDecimal.valueOf(5000));

           account.setCardId("625444548433");

           account.setDate(new Date());

           accounts.add(account);

           user.setAccounts(accounts);

    ObjectMapper mapper = new ObjectMapper();

           mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, Boolean.TRUE);

           String json = mapper.writeValueAsString(user);

           System.out.println("Java2Json: "+json);

           user = mapper.readValue(json, User.class);

           System.out.println("Json2Java: "+mapper.writeValueAsString(user));

    }

        mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, Boolean.TRUE);这是辅助设置,控制格式化输出。
        之前使用的mapper.getSerializationConfig().setXxx方法现在很多都已经被标注为@Deprecated了,因此请大家使用上面的方式处理。
        SerializationConfig.Feature枚举里面还有很多其它的设置项,比如日期,比如要不要输出null值等等。其它的还有:
            org.codehaus.jackson.JsonGenerator.Feature.* 
            org.codehaus.jackson.JsonParser.Feature.*
        让我们来看看输出结果,两次转换之后,打印出来的字符串应该是一样的:
        
        OK,果然结果是一致的,大家现在应该会使用jackson进行Java与Json的互相转换了吧?恩,现在再考虑一种情况,如果想将List<User>的JSON字符串反转为泛型,应该怎么做呢?
        想这样:mapper.readValue(json, List<User>.class)?这可是错误的,这里的参数是Class<T> valueType,valueType是Class<T>类的对象。如上面所示User.class 就是Class<User>类的对象。因此要想获得泛型的集合类型需要通过其它办法:

    /**
     * 获取泛型的Collection Type
     * @param jsonStr json字符串
     * @param collectionClass 泛型的Collection
     * @param elementClasses 元素类型
     */
    public static <T> T readJson(String jsonStr, Class<?> collectionClass, Class<?>... elementClasses) throws Exception {

           ObjectMapper mapper = new ObjectMapper();

           JavaType javaType = mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);

           return mapper.readValue(jsonStr, javaType);

    }

        定义一个List<User>,向里面添加两次user,先调用writeValueAsString方法打印出json,再调用readJson方法,这不仅可以转换泛型List<T>,还可以用于其它集合,比如Map<K,V>等等。
        List<User> list = readJson(json, List.class, User.class); 
        ObjectMapper可以让对象与JSON之间相互转换,除此之外Jackson还提供了JsonGenerator 和JsonParser 这两个类,它们可以更细粒度化。调用ObjectMapper的writeValueAsString和readValue方法,最终还是会交给JsonGenerator 和JsonParser 去处理,对此还有疑惑的话,可以去看看这两个方法的
    的处理序列化与反序列源码。

  • 相关阅读:
    dig批量获取域名对应IP
    文件和目录
    Linux程序设计的CD唱片应用程序
    LinuxRedhat7.0虚拟机配置双网卡
    Redhat7.0计划任务服务程序(at,crontab)
    RedHat7 修改主机名称 配置网卡信息 配置Yum软件仓库
    关于RedHat5.0不能提示找不到/media/cdrom/repodate/repomd.xml
    Redhat5静态IP分配,提示Error, some other host already uses address解决办法
    三种时间戳的解释
    RHEL 7 -解决“没有启用回购”消息
  • 原文地址:https://www.cnblogs.com/wangorg/p/4554130.html
Copyright © 2020-2023  润新知