ObjectMapper 的一些坑

相信做过Java 开发对这个类应该不陌生,没错,这个类是jackson提供的,主要是用来把对象转换成为一个json字符串返回到前端,

现在大部分数据交换都是以json来传输的,所以这个很重要,那你到底又对这个类有着有多少了解呢,下面我说一下我遇到的一些坑

首先,先把我要说的几个坑需要设置的属性贴出来先


   
   
  1. ObjectMapper objectMapper = new ObjectMapper();
  2. //序列化的时候序列对象的所有属性
  3. objectMapper.setSerializationInclusion(Include.ALWAYS);
  4. //反序列化的时候如果多了其他属性,不抛出异常
  5. objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  6. //如果是空对象的时候,不抛异常
  7. objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
  8. //取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式
  9. objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
  10. objectMapper.setDateFormat( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"))

简单说一下这个类的基本用法,以下采用代码块加截图的形式来说明和部分文字件数


   
   
  1. package com.shiro.test;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. import com.fasterxml.jackson.annotation.JsonInclude.Include;
  5. import com.fasterxml.jackson.databind.DeserializationFeature;
  6. import com.fasterxml.jackson.databind.ObjectMapper;
  7. import com.fasterxml.jackson.databind.SerializationFeature;
  8. public class Main2 {
  9. public static void main(String[] args) throws Exception{
  10. ObjectMapper objectMapper = new ObjectMapper();
  11. //序列化的时候序列对象的所有属性
  12. objectMapper.setSerializationInclusion(Include.ALWAYS);
  13. //取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式
  14. objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
  15. objectMapper.setDateFormat( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"));
  16. Person person = new Person( 1, "zxc", new Date());
  17. //这是最简单的一个例子,把一个对象转换为json字符串
  18. String personJson = objectMapper.writeValueAsString(person);
  19. System.out.println(personJson);
  20. //默认为true,会显示时间戳
  21. objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
  22. personJson = objectMapper.writeValueAsString(person);
  23. System.out.println(personJson);
  24. }
  25. }

输出的信息如下



objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)的作用



   
   
  1. package com.shiro.test;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. import com.fasterxml.jackson.annotation.JsonInclude.Include;
  5. import com.fasterxml.jackson.databind.DeserializationFeature;
  6. import com.fasterxml.jackson.databind.ObjectMapper;
  7. import com.fasterxml.jackson.databind.SerializationFeature;
  8. public class Main2 {
  9. public static void main(String[] args) throws Exception{
  10. ObjectMapper objectMapper = new ObjectMapper();
  11. //序列化的时候序列对象的所有属性
  12. objectMapper.setSerializationInclusion(Include.ALWAYS);
  13. //如果是空对象的时候,不抛异常,也就是对应的属性没有get方法
  14. objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
  15. Person person = new Person( 1, "zxc", new Date());
  16. String personJson = objectMapper.writeValueAsString(person);
  17. System.out.println(personJson);
  18. //默认是true,即会抛异常
  19. objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, true);
  20. personJson = objectMapper.writeValueAsString(person);
  21. System.out.println(personJson);
  22. }
  23. }
对应的person类此时为
   
   

   
   
  1. package com.shiro.test;
  2. import java.util.Date;
  3. public class Person {
  4. private Integer id;
  5. private String name;
  6. private Date birthDate;
  7. // public Integer getId() {
  8. // return id;
  9. // }
  10. // public void setId(Integer id) {
  11. // this.id = id;
  12. // }
  13. // public String getName() {
  14. // return name;
  15. // }
  16. // public void setName(String name) {
  17. // this.name = name;
  18. // }
  19. // public Date getBirthDate() {
  20. // return birthDate;
  21. // }
  22. // public void setBirthDate(Date birthDate) {
  23. // this.birthDate = birthDate;
  24. // }
  25. @Override
  26. public String toString() {
  27. return "Person [id=" + id + ", name=" + name + ", birthDate=" + birthDate + "]";
  28. }
  29. public Person(Integer id, String name, Date birthDate) {
  30. super();
  31. this.id = id;
  32. this.name = name;
  33. this.birthDate = birthDate;
  34. }
  35. public Person() {
  36. // TODO Auto-generated constructor stub
  37. }
  38. }

结果如下




   
   
  1. package com.shiro.test;
  2. import com.fasterxml.jackson.annotation.JsonInclude.Include;
  3. import com.fasterxml.jackson.databind.DeserializationFeature;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. public class Main2 {
  6. public static void main(String[] args) throws Exception{
  7. ObjectMapper objectMapper = new ObjectMapper();
  8. //序列化的时候序列对象的所有属性
  9. objectMapper.setSerializationInclusion(Include.ALWAYS);
  10. //反序列化的时候如果多了其他属性,不抛出异常
  11. objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  12. // Person person = new Person(1, "zxc", new Date());
  13. // String personJson = objectMapper.writeValueAsString(person);
  14. // System.out.println(personJson);
  15. //注意,age属性是不存在在person对象中的
  16. String personStr = "{\"id\":1,\"name\":\"zxc\",\"age\":\"zxc\"}";
  17. Person person = objectMapper.readValue(personStr, Person.class);
  18. System.out.println(person);
  19. //默认为true
  20. objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
  21. person = objectMapper.readValue(personStr, Person.class);
  22. System.out.println(person);
  23. }
  24. }

执行后的结果如下



这些便是这几个属性的作用所以,由于第一个比较简单我就这样说一下吧


Include.ALWAYS  是序列化对像所有属性

Include.NON_NULL 只有不为null的字段才被序列化

Include.NON_EMPTY 如果为null或者 空字符串和空集合都不会被序列化


然后再说一下如何把一个对象集合转换为一个 Java里面的数组


   
   
  1. package com.shiro.test;
  2. import java.util.ArrayList;
  3. import java.util.Date;
  4. import java.util.List;
  5. import com.fasterxml.jackson.annotation.JsonInclude.Include;
  6. import com.fasterxml.jackson.core.type.TypeReference;
  7. import com.fasterxml.jackson.databind.JavaType;
  8. import com.fasterxml.jackson.databind.ObjectMapper;
  9. public class Main2 {
  10. public static void main(String[] args) throws Exception{
  11. ObjectMapper objectMapper = new ObjectMapper();
  12. //序列化的时候序列对象的所有属性
  13. objectMapper.setSerializationInclusion(Include.NON_DEFAULT);
  14. Person person1 = new Person( 1, "zxc", new Date());
  15. Person person2 = new Person( 2, "ldh", new Date());
  16. List<Person> persons = new ArrayList<>();
  17. persons.add(person1);
  18. persons.add(person2);
  19. //先转换为json字符串
  20. String personStr = objectMapper.writeValueAsString(persons);
  21. //反序列化为List<user> 集合,1需要通过 TypeReference 来具体传递值
  22. List<Person> persons2 = objectMapper.readValue(personStr, new TypeReference<List<Person>>() {});
  23. for(Person person : persons2) {
  24. System.out.println(person);
  25. }
  26. //2,通过 JavaType 来进行处理返回
  27. JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, Person.class);
  28. List<Person> persons3 = objectMapper.readValue(personStr, javaType);
  29. for(Person person : persons3) {
  30. System.out.println(person);
  31. }
  32. }
  33. }
以上,是个人在项目遇到的部分坑,希望对大家有所帮助
  •                     <li class="tool-item tool-active is-like "><a href="javascript:;"><svg class="icon" aria-hidden="true">
                            <use xlink:href="#csdnc-thumbsup"></use>
                        </svg><span class="name">点赞</span>
                        <span class="count">11</span>
                        </a></li>
                        <li class="tool-item tool-active is-collection "><a href="javascript:;" data-report-click="{&quot;mod&quot;:&quot;popu_824&quot;}"><svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-csdnc-Collection-G"></use>
                        </svg><span class="name">收藏</span></a></li>
                        <li class="tool-item tool-active is-share"><a href="javascript:;"><svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-csdnc-fenxiang"></use>
                        </svg>分享</a></li>
                        <!--打赏开始-->
                                                <!--打赏结束-->
                                                <li class="tool-item tool-more">
                            <a>
                            <svg t="1575545411852" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5717" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M179.176 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5718"></path><path d="M509.684 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5719"></path><path d="M846.175 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5720"></path></svg>
                            </a>
                            <ul class="more-box">
                                <li class="item"><a class="article-report">文章举报</a></li>
                            </ul>
                        </li>
                                            </ul>
                </div>
                            </div>
            <div class="person-messagebox">
                <div class="left-message"><a href="https://blog.csdn.net/zxc_user">
                    <img src="https://profile.csdnimg.cn/1/8/4/3_zxc_user" class="avatar_pic" username="zxc_user">
                                            <img src="https://g.csdnimg.cn/static/user-reg-year/2x/3.png" class="user-years">
                                    </a></div>
                <div class="middle-message">
                                        <div class="title"><span class="tit"><a href="https://blog.csdn.net/zxc_user" data-report-click="{&quot;mod&quot;:&quot;popu_379&quot;}" target="_blank">zxc_user</a></span>
                                            </div>
                    <div class="text"><span>发布了98 篇原创文章</span> · <span>获赞 40</span> · <span>访问量 21万+</span></div>
                </div>
                                <div class="right-message">
                                            <a href="https://im.csdn.net/im/main.html?userName=zxc_user" target="_blank" class="btn btn-sm btn-red-hollow bt-button personal-letter">私信
                        </a>
                                                            <a class="btn btn-sm  bt-button personal-watch" data-report-click="{&quot;mod&quot;:&quot;popu_379&quot;}">关注</a>
                                    </div>
                            </div>
                    </div>
    
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值