package org.ccframe.commons.util; import java.io.IOException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.NullNode; /** * JSON 转换器.(jackson) * * Jim */ public class JsonBinder { private static Logger logger = LoggerFactory.getLogger(JsonBinder.class); private ObjectMapper mapper; private static JsonBinder normalBinder; private static JsonBinder nonNullBinder; public JsonNode toNode(String jsonString){ try { return mapper.readTree(jsonString); } catch (IOException e) { logger.error("json parse error:" + jsonString,e); return NullNode.getInstance(); } } public JsonNode objectToNode(Object object){ return toNode(toJson(object)); } private JsonBinder(Include inclusion) { mapper = new ObjectMapper(); //设置输出时包含属性的风格 mapper.setSerializationInclusion(inclusion); // mapper.getSerializationConfig().withSerializationInclusion(inclusion); //设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性 mapper.getDeserializationConfig().without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); } /** * 创建输出全部属性到Json字符串的Binder. */ public static synchronized JsonBinder buildNormalBinder() { if(normalBinder==null){ normalBinder = new JsonBinder(Include.ALWAYS); } return normalBinder; } /** * 创建只输出非空属性到Json字符串的Binder. */ public static synchronized JsonBinder buildNonNullBinder() { if(nonNullBinder==null){ nonNullBinder = new JsonBinder(Include.NON_NULL); } return nonNullBinder; } /** * 如果JSON字符串为Null或"null"字符串,返回Null. * 如果JSON字符串为"[]",返回空集合. * 如果需要返回数组,使用数据类型如Product[].class *
*/ public