@JsonSerialize&JsonDeserialize&mixin&module

 ObjectMapper mapper = new ObjectMapper();
 mapper.registerModule(new WebServletJackson2Module());
/**
 * Mixin class to serialize/deserialize {@link javax.servlet.http.Cookie}
 *
 * 
 *     ObjectMapper mapper = new ObjectMapper();
 *     mapper.registerModule(new WebServletJackson2Module());
 * 
* * @author Jitendra Singh * @see WebServletJackson2Module * @see org.springframework.security.jackson2.SecurityJackson2Modules * @since 4.2 */
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) @JsonDeserialize(using = CookieDeserializer.class) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, isGetterVisibility = JsonAutoDetect.Visibility.NONE) abstract class CookieMixin { }
/**
 * Jackson deserializer for {@link Cookie}. This is needed because in most cases we don't
 * set {@link Cookie#getDomain()} property. So when jackson deserialize that json {@link Cookie#setDomain(String)}
 * throws {@link NullPointerException}. This is registered with {@link CookieMixin} but you can also use it with
 * your own mixin.
 *
 * @author Jitendra Singh
 * @see CookieMixin
 * @since 4.2
 */
class CookieDeserializer extends JsonDeserializer<Cookie> {

	@Override
	public Cookie deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
		ObjectMapper mapper = (ObjectMapper) jp.getCodec();
		JsonNode jsonNode = mapper.readTree(jp);
		Cookie cookie = new Cookie(readJsonNode(jsonNode, "name").asText(), readJsonNode(jsonNode, "value").asText());
		cookie.setComment(readJsonNode(jsonNode, "comment").asText());
		cookie.setDomain(readJsonNode(jsonNode, "domain").asText());
		cookie.setMaxAge(readJsonNode(jsonNode, "maxAge").asInt(-1));
		cookie.setSecure(readJsonNode(jsonNode, "secure").asBoolean());
		cookie.setVersion(readJsonNode(jsonNode, "version").asInt());
		cookie.setPath(readJsonNode(jsonNode, "path").asText());
		cookie.setHttpOnly(readJsonNode(jsonNode, "httpOnly").asBoolean());
		return cookie;
	}

	private JsonNode readJsonNode(JsonNode jsonNode, String field) {
		return jsonNode.has(field) && !(jsonNode.get(field) instanceof NullNode) ? jsonNode.get(field) : MissingNode.getInstance();
	}
}

你可能感兴趣的:(#,jackson,spring)