把任意类型对象转化为json字符串(工具类)

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

public final class JacksonUtil {

private final static Logger log = LoggerFactory.getLogger(JacksonUtil.class);

private JacksonUtil() {
}

private static final ObjectMapper mapper = getNoNullValuesMapper(new ObjectMapper());

public static ObjectMapper getNoNullValuesMapper(ObjectMapper mapper) {
	mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
	mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
	return mapper;
}

/**
 * JSON to Bean.
 */
public static  T toBean(final String jsonString, Class clazz) throws IOException {
	return (T) mapper.readValue(jsonString, clazz);
}

/**
 * JSON to Bean.
 */
public static  T toBeanQuietly(final String jsonString, Class clazz) {
	try {
		return (T) mapper.readValue(jsonString, clazz);
	} catch (IOException e) {
		log.error("", e);
		return null;
	}
}

/**
 * to JSON.
 */
public static String toJsonString(final Object data) {
	Writer strWriter = new StringWriter();
	String jsonString = toJsonString(strWriter, data);
	try {
		strWriter.flush();
		strWriter.close();
	} catch (IOException e) {
		log.error("", e);
	}
	return jsonString;
}

/**
 * to JSON.
 */
public static String toJsonString(Writer strWriter, final Object data) {
	return toJsonString(mapper, strWriter, data);
}

/**
 * to JSON.
 */
public static String toJsonString(ObjectMapper mapper, Writer strWriter, final Object data) {
	try {
		mapper.writeValue(strWriter, data);
	} catch (JsonGenerationException e) {
		log.error("", e);
	} catch (JsonMappingException e) {
		log.error("", e);
	} catch (IOException e) {
		log.error("", e);
	}
	return strWriter.toString();
}

}

参考jar
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

jackson-annotations-2.0.0.jar
jackson-core-2.0.0.jar
jackson-databind-2.0.0.jar
日志jar
在这里插入图片描述
slf4j-api-1.6.6.jar

你可能感兴趣的:(web开发,java)