java类型之间的转换,通过objectMapper转换

本文详细介绍了Jackson库中@JsonInclude注解的四种模式及其作用,展示了如何使用ObjectMapper进行对象、Map、数组与JSON之间的转换。示例包括对象转json、Map转json、json转对象、json转Map以及json转对象数组和Map数组的转换方法。此外,还演示了如何处理日期格式以及将Bean转换为Map。
摘要由CSDN通过智能技术生成

1,在需要转化的实体类商添加如下注解

@JsonInclude(Include.NON_NULL) 
@JsonInclude(Include.Include.ALWAYS)// 默认 
@JsonInclude(Include.NON_DEFAULT) //属性为默认值不序列化 
@JsonInclude(Include.NON_EMPTY) //属性为 空(“”) 或者为 NULL 都不序列化 
@JsonInclude(Include.NON_NULL) //属性为NULL 不序列化 

在转换过程中有些属性被设置为空,这样就不需要转化

2,jackson objectMapper json字符串、对象bean、map、数组list互相转换常用的方法列举:

ObjectMapper mapper = new ObjectMapper();

  • 对象转json字符串
User user=new User();
String userJson=mapper.writeValueAsString(user);
  • Map转json字符串
Map map=new HashMap();  
String json=mapper.writeValueAsString(map);
  • 数组list转json字符串
Student[] stuArr = {student1, student3};  
String jsonfromArr =  mapper.writeValueAsString(stuArr);
  • json字符串转对象
String expected = "{\"name\":\"Test\"}";
User user = mapper.readValue(expected, User.class);
  • json字符串转Map
String expected = "{\"name\":\"Test\"}";
Map userMap = mapper.readValue(expected, Map.class);
  • json字符串转对象数组List
String expected="[{\"a\":12},{\"b\":23},{\"name\":\"Ryan\"}]";
CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, User.class);
List<User> userList = mapper.readValue(expected, listType);
  • json字符串转Map数组List<Map<String,Object>>
String expected="[{\"a\":12},{\"b\":23},{\"name\":\"Ryan\"}]";
CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Map.class);
List<Map<String,Object>> userMapList = mapper.readValue(expected, listType);
  • jackson默认将对象转换为LinkedHashMap:
String expected = "[{\"name\":\"Ryan\"},{\"name\":\"Test\"},{\"name\":\"Leslie\"}]";
ArrayList arrayList = mapper.readValue(expected, ArrayList.class);
  • json字符串与list或map互转的方法
ObjectMapper objectMapper = new ObjectMapper();
 //遇到date按照这种格式转换
 SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 objectMapper.setDateFormat(fmt);
 
  String preference = "{name:'侯勇'}";
        //json字符串转map
  Map<String, String> preferenceMap = new HashMap<String, String>();
  preferenceMap = objectMapper.readValue(preference, preferenceMap.getClass());
  
  //map转json字符串
  String result=objectMapper.writeValueAsString(preferenceMap);
  • bean转换为map
List<Map<String,String>> returnList=new ArrayList<Map<String,String>>();
List<Menu> menuList=menuDAOImpl.findByParentId(parentId);
ObjectMapper mapper = new ObjectMapper();
//用jackson将bean转换为map
returnList=mapper.convertValue(menuList,new TypeReference<List<Map<String, String>>>(){});
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值