使用jackson工具类objectMapper对象实现 json字符串与对象bean、map、list互相转换

 



Object转Map和Map转Object(对象转map,map转对象)

FindArchiveDto findArchiveDto = new FindArchiveDto();
findArchiveDto.setContractStatus("降龙");
findArchiveDto.setCustName("明华");
findArchiveDto.setDepartmentName("赵无极");



fastjson转换方法:

//Object转Map
Map map = JSONObject.parseObject(JSONObject.toJSONString(findArchiveDto), Map.class);
Map<String,Object> map = JSONObject.parseObject(JSON.toJSONString(findArchiveDto));
//Map转Object
FindArchiveDto findArchiveDto1 = JSON.parseObject(JSON.toJSONString(map), FindArchiveDto.class);
FindArchiveDto findArchiveDto2 = JSONObject.toJavaObject(JSON.toJSONString(map), FindArchiveDto.class);



jackson的转换:

ObjectMapper mapper = new ObjectMapper();
//对象转map
Map m = mapper.readValue(mapper.writeValueAsString(findArchiveDto), Map.class);
//map转对象
FindArchiveDto dto = mapper.readValue(mapper.writeValueAsString(m), FindArchiveDto.class);

 一个对应的简单的工具类

private static final ObjectMapper mapper = new ObjectMapper();

    // 将对象转成字符串
    public static String objectToString(Object obj) throws Exception {
        return mapper.writeValueAsString(obj);
    }
    // 将Map转成指定的Bean
    public static Object mapToBean(Map map, Class clazz) throws Exception {
        return mapper.readValue(objectToString(map), clazz);
    }
    // 将Bean转成Map
    public static Map beanToMap(Object obj) throws Exception {
        return mapper.readValue(objectToString(obj), Map.class);
    }

 



使用jackson工具类objectMapper对象实现 json字符串与对象bean、map、list互相转换



工具类:

// spring自带的jackson工具类,可以使用它进行序列化实现格式转换
  private static final 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\":\"zhangsan\"}";
User user = mapper.readValue(expected, User.class);



5.json字符串转Map

String expected = "{\"name\":\"zhangsan\"}";
Map userMap = mapper.readValue(expected, Map.class);



6.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);



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:'zhangsan'}";
        //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>>>(){});



11.数组和对象直接的转换:

//对象转为byte数组
byte[] byteArr = mapper.writeValueAsBytes(student);
System.out.println(byteArr);
 
 
//byte数组转为对象
Student student= mapper.readValue(byteArr, Student.class);
System.out.println(student);

 



备注ObjectMapper生成后的一些常见可能需要的配置:

//创建ObjectMapper对象
    mapper = new ObjectMapper()
 
    //configure方法 配置一些需要的参数
    // 转换为格式化的json 显示出来的格式美化
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
 
   //序列化的时候序列对象的那些属性  
   //JsonInclude.Include.NON_DEFAULT 属性为默认值不序列化 
   //JsonInclude.Include.ALWAYS      所有属性
   //JsonInclude.Include.NON_EMPTY   属性为 空(“”) 或者为 NULL 都不序列化 
   //JsonInclude.Include.NON_NULL    属性为NULL 不序列化
   mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);  
 
   
    //反序列化时,遇到未知属性会不会报错 
    //true - 遇到没有的属性就报错 false - 没有的属性不会管,不会报错
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 
    //如果是空对象的时候,不抛异常  
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);  
 
    // 忽略 transient 修饰的属性
    mapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);
 
    //修改序列化后日期格式
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);  
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
 
   //处理不同的时区偏移格式
   mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
   mapper.registerModule(new JavaTimeModule());