Skip to content

Instantly share code, notes, and snippets.

@logicjwell
Last active April 26, 2019 09:28
Show Gist options
  • Save logicjwell/e47534ee3292c9b0502aaa6fc2ef0a98 to your computer and use it in GitHub Desktop.
Save logicjwell/e47534ee3292c9b0502aaa6fc2ef0a98 to your computer and use it in GitHub Desktop.
[jackson 工具函数] #jackson
private final static ObjectMapper OBJECT_MAPPER=new ObjectMapper();
static {
OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
OBJECT_MAPPER.configure(SerializationFeature.INDENT_OUTPUT, Boolean.TRUE);
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
/**
* <p>
* 对象转JSON字符串
* </p>
*/
public static String object2Json(Object obj) {
try {
String string = OBJECT_MAPPER.writeValueAsString(object);
return string;
} catch (JsonProcessingException e) {
log.error("在序列化对象为json字符串时遇到错误",e);
return "";
}
}
public static Map object2Map(Object obj) {
String object2Json = object2Json(obj);
Map<?, ?> result = jsonToMap(object2Json);
return result;
}
/**
* <p>
* JSON字符串转Map对象
* </p>
*/
public static Map<?, ?> jsonToMap(String json) {
return json2Object(json, Map.class);
}
/**
* <p>
* JSON转Object对象
* </p>
*/
public static <T> T json2Object(String json, Class<T> cls) {
T result = null;
try {
result = OBJECT_MAPPER.readValue(json, cls);
} catch (IOException e) {
log.error("在将json字符串反序列化时遇到错误",e);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment