Jackson 框架,轻易转换JSON

Jackson的jar 下载地址:http://jackson.codehaus.org/1.7.6/jackson-all-1.7.6.jar

官网例子:http://wiki.fasterxml.com/JacksonInFiveMinutes

代码示例

package org.springframework.mvc.demo.common;

import java.io.StringWriter;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class JsonUtils {
	private static final Logger logger   = LoggerFactory.getLogger(JsonUtils.class);

	private static final ObjectMapper mapper = new ObjectMapper();

	public static String jsonFromObject(Object object) {

		StringWriter writer = new StringWriter();

		try {

			mapper.writeValue(writer, object);

		} catch (RuntimeException e) {

			throw e;

		} catch (Exception e) {

			logger.error("Unable to serialize to json: " + object, e);

			return null;

		}

		return writer.toString();

	}


	public static <T> T objectFromJson(String json, Class<T> klass) {

		T object;

		try {

			object = mapper.readValue(json, klass);

		} catch (RuntimeException e) {

			logger.error("Runtime exception during deserializing "

			+ klass.getSimpleName() + " from "

			+ StringUtils.abbreviate(json, 80));

			throw e;

		} catch (Exception e) {

			logger.error("Exception during deserializing " + klass.getSimpleName()

			+ " from " + StringUtils.abbreviate(json, 80));

			return null;

		}

		return object;

	}
}

 

你可能感兴趣的:(Jackson)