jackson反序列化器获取类型

简介: jackson反序列化器获取类型

不要用陌生人的目光来看你所爱的人,也不要认为自己做出了牺牲——贝·列昂尼多娃

例如这里使用hutool的EnumUtil.getEnumAt传入枚举的ordinal,以及枚举类型,获取到具体的枚举常量值

import cn.hutool.core.util.EnumUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import java.io.IOException;
/**
 * @author VampireAchao
 * @since 2023/1/12 15:46
 */
public class EnumOrdinalDeSerializer<E extends Enum<E>> extends JsonDeserializer<E> implements ContextualDeserializer {
    private JavaType type;
    public EnumOrdinalDeSerializer() {
    }
    public EnumOrdinalDeSerializer(JavaType type) {
        this.type = type;
    }
    /**
     * Method that can be called to ask implementation to deserialize
     * JSON content into the value type this serializer handles.
     * Returned instance is to be constructed by method itself.
     * <p>
     * Pre-condition for this method is that the parser points to the
     * first event that is part of value to deserializer (and which
     * is never JSON 'null' literal, more on this below): for simple
     * types it may be the only value; and for structured types the
     * Object start marker or a FIELD_NAME.
     * </p>
     * <p>
     * The two possible input conditions for structured types result
     * from polymorphism via fields. In the ordinary case, Jackson
     * calls this method when it has encountered an OBJECT_START,
     * and the method implementation must advance to the next token to
     * see the first field name. If the application configures
     * polymorphism via a field, then the object looks like the following.
     * <pre>
     *      {
     *          "@class": "class name",
     *          ...
     *      }
     *  </pre>
     * Jackson consumes the two tokens (the <tt>@class</tt> field name
     * and its value) in order to learn the class and select the deserializer.
     * Thus, the stream is pointing to the FIELD_NAME for the first field
     * after the @class. Thus, if you want your method to work correctly
     * both with and without polymorphism, you must begin your method with:
     * <pre>
     *       if (p.currentToken() == JsonToken.START_OBJECT) {
     *         p.nextToken();
     *       }
     *  </pre>
     * This results in the stream pointing to the field name, so that
     * the two conditions align.
     * <p>
     * Post-condition is that the parser will point to the last
     * event that is part of deserialized value (or in case deserialization
     * fails, event that was not recognized or usable, which may be
     * the same event as the one it pointed to upon call).
     * <p>
     * Note that this method is never called for JSON null literal,
     * and thus deserializers need (and should) not check for it.
     *
     * @param p    Parsed used for reading JSON content
     * @param ctxt Context that can be used to access information about
     *             this deserialization activity.
     * @return Deserialized value
     */
    @Override
    public E deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        return EnumUtil.getEnumAt((Class<E>) type.getRawClass(), p.getValueAsInt());
    }
    /**
     * Method called to see if a different (or differently configured) deserializer
     * is needed to deserialize values of specified property.
     * Note that instance that this method is called on is typically shared one and
     * as a result method should <b>NOT</b> modify this instance but rather construct
     * and return a new instance. This instance should only be returned as-is, in case
     * it is already suitable for use.
     *
     * @param ctxt     Deserialization context to access configuration, additional
     *                 deserializers that may be needed by this deserializer
     * @param property Method, field or constructor parameter that represents the property
     *                 (and is used to assign deserialized value).
     *                 Should be available; but there may be cases where caller cannot provide it and
     *                 null is passed instead (in which case impls usually pass 'this' deserializer as is)
     * @return Deserializer to use for deserializing values of specified property;
     * may be this instance or a new instance.
     * @throws JsonMappingException
     */
    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
        //beanProperty is null when the type to deserialize is the top-level type or a generic type, not a type of a bean property
        JavaType type = ctxt.getContextualType() != null
                ? ctxt.getContextualType()
                : property.getMember().getType();
        return new EnumOrdinalDeSerializer<>(type);
    }
}


使用:

class Entity{
    @JsonDeserialize(using = EnumOrdinalDeSerializer.class)
    private MyEnum myEnum;
}
相关文章
|
Linux 编译器 C++
C/C++性能优化:从根本上消除拷贝操作的浪费
C/C++性能优化:从根本上消除拷贝操作的浪费
2061 1
|
6月前
|
存储 人工智能 自然语言处理
Skills实战:从0到1封装一个“登录鉴权”Skill,拿来即用
本文直击AI Agent落地痛点——登录鉴权失效、状态丢失、提示词不可靠。提出以“Skill”替代传统提示词工程:将动态认证逻辑(如Token获取/刷新/存储)封装为可复用、带状态管理的代码模块,实现跨会话稳定调用。实战拆解Skill四要素,揭示其如何让AI“一次登录,全程无忧”。
|
10月前
|
消息中间件 Java 关系型数据库
吃透 Java 轻量级流程引擎 Easy Work:从核心原理到生产级落地全指南
Easy Work是一款开源轻量级Java流程引擎,基于状态机设计,摒弃BPMN复杂特性,学习成本降90%、性能提升3倍以上,专为中小微流程场景优化,5分钟即可快速集成上线。
1514 2
|
前端开发 容灾 应用服务中间件
云服务器购买的新数据盘,如何进行分区、挂载新目录?
云服务器购买的新数据盘,如何进行分区、挂载新目录?
1970 0
|
6月前
|
人工智能 安全 定位技术
CodeGraph深度解析 让Claude Code工具调用直降七成的核心原理与实操教程
如今以Claude Code为代表的AI编程智能体已经成为开发者日常编码、项目重构、漏洞修复的必备工具。但在长期使用过程中,几乎所有开发者都会遇到同一个明显痛点:AI虽然具备强大的代码生成与分析能力,却常常陷入盲目探索的循环中。
2618 4
|
10月前
|
安全 开发工具 git
别再瞎用 Git 合并了!Merge vs Rebase 底层逻辑、适用场景与零坑操作全指南
本文深度解析Git中Merge与Rebase的本质区别:Merge安全可追溯,适合公共分支合并;Rebase线性整洁,仅限本地私有分支整理。从底层对象模型出发,结合实战示例与企业级最佳实践,厘清使用红线、避坑误区,助你彻底掌握分支合并决策逻辑。(239字)
2043 2
|
12月前
|
人工智能 自然语言处理 搜索推荐
AI客服选型指南:2025年12月主流智能客服系统产品测评
随着企业数字化加速,智能客服正向全渠道、智能化、情感化演进,成为服务与增长双引擎。本文详解瓴羊Quick Service、智齿科技等主流厂商的核心优势与适用场景,并从需求匹配、智能化水平、集成能力等维度提供选型指南,展望情感计算、多模态交互与业务融合的未来趋势,助力企业高效决策。瓴羊 Quick Service 依托阿里巴巴20年服务运营经验与阿里云全球基础设施,为企业提供全渠道、全链路、全场景的智能客服解决方案,覆盖售前咨询、售中支持、售后维护全流程,适配零售、电商、汽车、互联网等多行业需求。
|
Kubernetes Cloud Native Nacos
nacos3.0
Nacos 3.0实现从配置中心到云原生控制面的跃迁,通过引入JRaft提升集群性能与稳定性,支持gRPC和xDS协议,打通服务网格生态,构建统一、可扩展的多集群服务治理平台,成为云原生基础设施的核心控制中枢。
|
12月前
|
安全
HTTP协议中请求方式GET 与 POST 什么区别 ?
简介:项目开发中常见GET与POST请求方式,主要区别在于参数传递位置、大小限制及安全性。GET用于获取数据,参数在URL中;POST用于提交数据,参数在请求体中,更安全。现代项目多采用RESTful风格,通过URL定位资源,不同请求方式(GET/POST/PUT/DELETE)对应不同操作,提升接口规范性与可读性。(238字)
|
12月前
|
JSON 安全 fastjson
使用阿里巴巴 Fastjson 替代 Spring Boot 默认的 Jackson
本文介绍在 Spring Boot 项目中如何替换默认的 Jackson,集成阿里巴巴 Fastjson 作为 JSON 处理框架。内容涵盖 Fastjson 与 Jackson 的核心对比、依赖配置、自定义消息转换器、null 值统一处理及循环引用控制,并提供安全建议与最佳实践,助你高效、安全地使用 Fastjson。