alibaba之jackson的ObjectMapper工具类封装

转于学习视频里的一工具类:

package com.example.demo.test;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;


import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.core.type.TypeReference;

public class JSONUtils {

	private static ObjectMapper objectMapper = new ObjectMapper();
	
	static {
		// 全部字段序列化
		//对象的所有字段全部列入
		objectMapper.setSerializationInclusion(Include.ALWAYS);
        //取消默认转换timestamps形式
		objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
        //所有的日期格式都统一为以下的样式,即yyyy-MM-dd HH:mm:ss
		objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		//忽略空Bean转json的错误
		objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
        //忽略 在json字符串中存在,但是在java对象中不存在对应属性的情况。防止错误
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
	}
	
	/**
	 * 
	 * @param obj
	 * @return
	 */
	public static <T> String obj2String(T obj){
        if(obj == null){
            return null;
        }
        try {
            return obj instanceof String ? (String)obj :  objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
	
	/**
	 * 有格式的
	 * @param obj
	 * @return
	 */
	public static <T> String obj2StringPretty(T obj){
        if(obj == null){
            return null;
        }
        try {
            return obj instanceof String ? (String)obj :  objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (Exception e) {
        	e.printStackTrace();
            return null;
        }
    }
	
	/**
	 * 字符串转对象
	 * @param str
	 * @param clazz
	 * @return
	 */
	public static <T> T string2Obj(String str,Class<T> clazz){
        if(StringUtils.isEmpty(str) || clazz == null){
            return null;
        }

        try {
            return clazz.equals(String.class)? (T)str : objectMapper.readValue(str,clazz);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
	
	/**
	 * 字段符转List之类的集合
	 * @param str
	 * @param typeReference
	 * @return
	 */
	public static <T> T string2Obj(String str, TypeReference typeReference){
        if(StringUtils.isEmpty(str) || typeReference == null){
            return null;
        }
        try {
            return (T)(typeReference.getType().equals(String.class)? str : objectMapper.readValue(str,typeReference));
        } catch (Exception e) {
        	e.printStackTrace();
            return null;
        }
    }
	
	/**
	 * 差不多同上
	 * @param str
	 * @param collectionClass
	 * @param elementClasses
	 * @return
	 */
	public static <T> T string2Obj(String str,Class<?> collectionClass,Class<?>... elementClasses){
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);
        try {
            return objectMapper.readValue(str,javaType);
        } catch (Exception e) {
        	e.printStackTrace();
            return null;
        }
    }
	
	public static void main(String[] args) {
		
		JSONUtils js = new JSONUtils();
		User u = new User(1L,"ywj", 123, new Date());
		User u2 = new User();
		System.out.println(js.obj2String(u));
		System.out.println(js.obj2StringPretty(u2));
		String str = js.obj2String(u);
		
		User u3 = js.string2Obj(str, User.class);
		System.out.println(u3.getName());
		// 加了属性减了属性
		User u5 = js.string2Obj("{\"id\":1,\"name\":\"ywj\",\"age2222\":123,\"date\":\"2018-01-14 22:14:18\",\"abc\":\"abc\"}", User.class);
		System.out.println(u5.getName());
		
		List<User> list = new ArrayList<User>();
		list.add(new User(1L,"ywj", 123, new Date()));
		list.add(new User(2L,"ywj2", 123, new Date()));
		str = js.obj2String(list);
		System.out.println(str);
		
		list = js.string2Obj(str, new TypeReference<List<User>>() {});
		System.out.println(list.size()+":"+list.get(1).getName());
		
		list = js.string2Obj(str, List.class, User.class);
		System.out.println(list.size()+":"+list.get(1).getName());
	}
}

OK

猜你喜欢

转载自blog.csdn.net/u013845177/article/details/79059914