@JsonSerialize&JsonDeserialize&mixin&module

 ObjectMapper mapper = new ObjectMapper();
 mapper.registerModule(new WebServletJackson2Module());
/**
 * Mixin class to serialize/deserialize {@link javax.servlet.http.Cookie}
 *
 * <pre>
 *     ObjectMapper mapper = new ObjectMapper();
 *     mapper.registerModule(new WebServletJackson2Module());
 * </pre>
 *
 * @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();
	}
}

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值