com.fasterxml.jackson使用笔记


  • Maven包依赖:

	com.fasterxml.jackson.dataformat
	jackson-dataformat-xml
	2.3.2


	com.fasterxml.jackson.core
	jackson-databind
	2.3.2

  • 对象或对象集合转Json时日期格式处理
public static String Array2Json(Object array) throws RuntimeException {
	String result = "";
	ObjectMapper mapper = new ObjectMapper();
	try {
		mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		result = mapper.writeValueAsString(array);
	} catch (Exception e) {
		log.error("JacksonUtil Exception>>>>>>>:{}", e.toString());
		throw new RuntimeException(e);
	}
	return result;
}
  • Jackson对象节点创建及使用
public static String wrapSuccessString(String status, String jsonSource) {
	String result = null;
	ObjectMapper mapper = new ObjectMapper();
	try {
		ObjectNode node = mapper.createObjectNode();
		node.put("status", status);
		node.put("value", mapper.readTree(jsonSource));

		result = mapper.writeValueAsString(node);
	} catch (JsonProcessingException e) {
		throw new RuntimeException(e);
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
	return result;
}
数组节点创建类似,用下面的语句:
	ArrayNode arr = mapper.createArrayNode();




你可能感兴趣的:(com.fasterxml.jackson使用笔记)