1. 程式人生 > >json和物件的相互轉化

json和物件的相互轉化

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">使用com.fasterxml.jackson.databind.ObjectMapper轉化物件和json字串</span>

Bean物件到json字串

private static String toJson(Object obj){
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		try {
			return objectMapper.writeValueAsString(obj);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

json字串到Bean
private static <T> T toObject(String content, Class<T> valueType) {
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		try {
			return objectMapper.readValue(content, valueType);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}