ObjectMapper mapper = new ObjectMapper();
1.对象转json字符串
User user=new User(); String userJson=mapper.writeValueAsString(user);
2.Map转json字符串
Map map=new HashMap(); String json=mapper.writeValueAsString(map);
3.数组list转json字符串
Student[] stuArr = {student1, student3};
String jsonfromArr = mapper.writeValueAsString(stuArr);
4.json字符串转对象
String expected = "{\"name\":\"Test\"}";
User user = mapper.readValue(expected, User.class);
5.json字符串转Map
String expected = "{\"name\":\"Test\"}";
Map userMap = mapper.readValue(expected, Map.class);
6.json字符串转对象数组List<object>
String expected="[{\"a\":12},{\"b\":23},{\"name\":\"Ryan\"}]";
CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, User.class);
List<User> userList = mapper.readValue(expected, listType);
7.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);
8.jackson默认将对象转换为LinkedHashMap:
String expected = "[{\"name\":\"Ryan\"},{\"name\":\"Test\"},{\"name\":\"Leslie\"}]";
ArrayList arrayList = mapper.readValue(expected, ArrayList.class);
9.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);
10.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>>>(){});
本文详细介绍使用Jackson库进行JSON数据与Java对象之间的转换方法,包括对象、Map、数组、List的相互转换,以及如何自定义日期格式。通过实例演示了如何将Java对象序列化为JSON字符串,以及如何将JSON字符串反序列化为Java对象。
1945

被折叠的 条评论
为什么被折叠?



