利用jackson-mapper-asl.jar实现对象和json格式的字符串之间的相互转换,在pom.xml文件中引入:
org.codehaus.jackson jackson-core-asl 1.9.13 org.codehaus.jackson jackson-mapper-asl 1.9.13
代码实现:
import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider; import org.codehaus.jackson.type.TypeReference; /** * String和对象相互转化工具 */ public class JsonMapper { private static ObjectMapper objectMapper = new ObjectMapper(); static { // config objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES); objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false)); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY); } public staticString obj2String(T src) { if (src == null) { return null; } try { return src instanceof String ? (String) src : objectMapper.writeValueAsString(src); } catch (Exception e) { log.warn("parse object to String exception, error:{}", e); return null; } } public static T string2Obj(String src, TypeReference typeReference) { if (src == null || typeReference == null) { return null; } try { return (T) (typeReference.getType().equals(String.class) ? src : objectMapper.readValue(src, typeReference)); } catch (Exception e) { log.warn("parse String to Object exception, String:{}, TypeReference :{}, error:{}", src, typeReference.getType(), e); return null; } } }