java中Json序列化和反序列化

package util;

import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonHelper {

	public static String toJson(Object object) throws JsonProcessingException {
		ObjectMapper objectMapper = new ObjectMapper();
		// 字段值为null时不序列化
		objectMapper.setSerializationInclusion(Include.NON_NULL);
		// 忽略未知字段
		objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		return objectMapper.writeValueAsString(object);
	}

	public static <T> T parseJson(String json, Class<T> clz)
			throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		// 字段值为null时不序列化
		objectMapper.setSerializationInclusion(Include.NON_NULL);
		// 忽略未知字段
		objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		return objectMapper.readValue(json, clz);
	}

}

posted on 2016-01-07 15:02  仗帅闯江湖  阅读(46)  评论(0编辑  收藏  举报

导航