`

Jackson自定义转换器

 
阅读更多

使用jackson进行json和java bean转换时,可以使用注解自定义转换器进行转换。

 

@JsonDeserialize注解源码
方法注释中写了,using 方法是作用在method上的。

 

package com.fasterxml.jackson.databind.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.KeyDeserializer;
import com.fasterxml.jackson.databind.util.Converter;

/**
 * Annotation use for configuring deserialization aspects, by attaching
 * to "setter" methods or fields, or to value classes.
 * When annotating value classes, configuration is used for instances
 * of the value class but can be overridden by more specific annotations
 * (ones that attach to methods or fields).
 *<p>
 * An example annotation would be:
 *<pre>
 *  &#64;JsonDeserialize(using=MySerializer.class,
 *    as=MyHashMap.class,
 *    keyAs=MyHashKey.class,
 *    contentAs=MyHashValue.class
 *  )
 *</pre>
 *<p>
 * Something to note on usage:
 *<ul>
 * <li>All other annotations regarding behavior during building should be on <b>Builder</b>
 *    class and NOT on target POJO class: for example &#64;JsonIgnoreProperties should be on
 *    Builder to prevent "unknown property" errors.
 *  </li>
 * <li>Similarly configuration overrides (see {@link com.fasterxml.jackson.databind.ObjectMapper#configOverride})
 *    should be targeted at Builder class, not target POJO class.
 *  </li>
 * </ul>
 *
 */
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.TYPE, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@com.fasterxml.jackson.annotation.JacksonAnnotation
public @interface JsonDeserialize
{
    // // // Annotations for explicitly specifying deserialize/builder

    /**
     * Deserializer class to use for deserializing associated value.
     * Depending on what is annotated,
     * value is either an instance of annotated class (used globablly
     * anywhere where class deserializer is needed); or only used for
     * deserializing property access via a setter method.
     */
    @SuppressWarnings("rawtypes") // to work around JDK8 bug wrt Class-valued annotation properties
    public Class<? extends JsonDeserializer> using()
        default JsonDeserializer.None.class;

    /**
     * Deserializer class to use for deserializing contents (elements
     * of a Collection/array, values of Maps) of annotated property.
     * Can only be used on instances (methods, fields, constructors),
     * and not value classes themselves.
     */
    @SuppressWarnings("rawtypes") // to work around JDK8 bug wrt Class-valued annotation properties
    public Class<? extends JsonDeserializer> contentUsing()
        default JsonDeserializer.None.class;

    /**
     * Deserializer class to use for deserializing Map keys
     * of annotated property.
     * Can only be used on instances (methods, fields, constructors),
     * and not value classes themselves.
     */
    public Class<? extends KeyDeserializer> keyUsing()
        default KeyDeserializer.None.class;

    /**
     * Annotation for specifying if an external Builder class is to
     * be used for building up deserialized instances of annotated
     * class. If so, an instance of referenced class is first constructed
     * (possibly using a Creator method; or if none defined, using default
     * constructor), and its "with-methods" are used for populating fields;
     * and finally "build-method" is invoked to complete deserialization.
     */
    public Class<?> builder() default Void.class;

    // // // Annotations for specifying intermediate Converters (2.2+)
    
    /**
     * Which helper object (if any) is to be used to convert from Jackson-bound
     * intermediate type (source type of converter) into actual property type
     * (which must be same as result type of converter). This is often used
     * for two-step deserialization; Jackson binds data into suitable intermediate
     * type (like Tree representation), and converter then builds actual property
     * type.
     *
     * @since 2.2
     */
    @SuppressWarnings("rawtypes") // to work around JDK8 bug wrt Class-valued annotation properties
    public Class<? extends Converter> converter() default Converter.None.class;

    /**
     * Similar to {@link #converter}, but used for values of structures types
     * (List, arrays, Maps).
     *
     * @since 2.2
     */
    @SuppressWarnings("rawtypes") // to work around JDK8 bug wrt Class-valued annotation properties
    public Class<? extends Converter> contentConverter() default Converter.None.class;
    
    
    // // // Annotations for explicitly specifying deserialization type
    // // // (which is used for choosing deserializer, if not explicitly
    // // // specified

    /**
     * Concrete type to deserialize values as, instead of type otherwise
     * declared. Must be a subtype of declared type; otherwise an
     * exception may be thrown by deserializer.
     *<p>
     * Bogus type {@link Void} can be used to indicate that declared
     * type is used as is (i.e. this annotation property has no setting);
     * this since annotation properties are not allowed to have null value.
     *<p>
     * Note: if {@link #using} is also used it has precedence
     * (since it directly specified
     * deserializer, whereas this would only be used to locate the
     * deserializer)
     * and value of this annotation property is ignored.
     */
    public Class<?> as() default Void.class;

    /**
     * Concrete type to deserialize keys of {@link java.util.Map} as,
     * instead of type otherwise declared.
     * Must be a subtype of declared type; otherwise an exception may be
     * thrown by deserializer.
     */
    public Class<?> keyAs() default Void.class;

    /**
     * Concrete type to deserialize content (elements
     * of a Collection/array, values of Maps) values as,
     * instead of type otherwise declared.
     * Must be a subtype of declared type; otherwise an exception may be
     * thrown by deserializer.
     */
    public Class<?> contentAs() default Void.class;
}
 

 

 

1.以日期类型为例

@JsonDeserialize(using= DateJsonDeserializer.class) // Json ==> Bean,需要写到Setter方法上
public void setCreateTime(Date createTime) {
    this.createTime = createTime;
}

@JsonSerialize(using= DateJsonSerializer.class) // Bean ==> Json,需要写到Getter方法上
public Date getCreateTime() {
    return createTime;
}

 

自定义转换方法: 

public class DateJsonDeserializer extends JsonDeserializer<Date> {
	public static final SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Override
	public Date deserialize(com.fasterxml.jackson.core.JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, com.fasterxml.jackson.core.JsonProcessingException {
 
		try {
			if(jsonParser!=null&&StringUtils.isNotEmpty(jsonParser.getText())){
				return format.parse(jsonParser.getText());
			}else {
				return null;
			}
 
		} catch(Exception e) {
			System.out.println(e.getMessage());
			throw new RuntimeException(e);
		}
	}

}

 

public class DateJsonSerializer extends JsonSerializer<Date> {
	public static final SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
	@Override
	public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
		jsonGenerator.writeString(format.format(date));
	}

}

 

分享到:
评论

相关推荐

    SpringBoot中自定义消息转换器示例源码

    Spring Boot默认提供了多种消息转换器,如FastjsonHttpMessageConverter、Jackson的MappingJackson2HttpMessageConverter等。然而,在某些特定场景下,我们可能需要自定义消息转换器来满足特定的序列化或反序列化...

    enum-converter:枚举的自定义转换器

    这就是"enum-converter"所解决的问题——提供枚举的自定义转换器。 枚举的自定义转换器主要是为了在不同数据格式之间进行枚举的转换,例如将枚举值转换为字符串、整数或其他类型,以便于存储和传输。在Java中,我们...

    springmvc自定义属性编辑器和参数解析器

    自定义属性编辑器需要继承`java.beans.PropertyEditorSupport`类,并重写`setAsText()`和`getAsText()`方法,前者用于将文本转换为对象,后者则是将对象转换为字符串。注册自定义属性编辑器可以通过`@InitBinder`...

    jackson-annotations、jackson-core、jackson-databind

    在Spring MVC中,你需要确保配置了正确的MVC消息转换器来支持JSON。 要解决这个问题,你可以按照以下步骤操作: 1. 在Spring MVC配置中添加Jackson的依赖,确保版本与Spring 4兼容,比如使用Jackson 2.9系列。 2. ...

    ActiveMQ与spring集成实例之使用消息转换器

    Spring 提供了多种内置的消息转换器,如 `SimpleMessageConverter` 和 `XmlMessageConverter`,但也可以自定义转换器。 例如,如果我们要将 Java 对象转换为 JSON 格式并发送,可以使用 Jackson 库配合 `...

    Jackson 配置json解析器

    标题中的“Jackson配置json解析器”指的是使用Jackson库来设置和管理JSON数据的解析过程。在这个场景中,我们看到的三个文件——`jackson-core-2.5.4.jar`, `jackson-annotations-2.5.4.jar`, `jackson-databind-...

    jackson依赖jar包.

    例如,`@JsonProperty`、`@JsonInclude`、`@JsonAutoDetect`等,这些注解可以帮助自定义JSON映射过程,确保数据的正确转换。 2. **jackson-core-2.2.3.jar**:这是Jackson的核心模块,包含了基本的JSON解析和生成...

    资源转换器,资源转换器程序,Java源码.zip

    资源转换器是一种软件工具,主要用于将一种格式的资源文件转换为另一种格式,以适应不同的应用场景或平台需求。在IT行业中,资源文件可能包括图像、音频、视频、文本、配置文件等,它们通常需要根据目标系统的要求...

    Jackson包(适合spring4.X版本的使用)

    1. **配置Spring**:在Spring的配置文件中,可以通过`&lt;mvc:annotation-driven&gt;`标签启用基于注解的控制器,这会自动配置Jackson作为默认的HTTP消息转换器。 2. **序列化与反序列化**:通过`ObjectMapper`,可以方便...

    jackson的jar包

    在SpringMVC中,Jackson作为默认的HTTP消息转换器,负责将Controller方法返回的对象转换成JSON响应,并将请求中的JSON数据转换为Java对象。通过配置SpringMVC的`MappingJackson2HttpMessageConverter`或`Jackson2...

    jackson-core-2.5.0.jar

    `MappingJackson2HttpMessageConverter`是Spring MVC中默认的JSON消息转换器,它依赖于Jackson的核心库来处理HTTP请求和响应的JSON数据。通过自定义`MessageConverter`或者调整Spring的配置,我们可以定制Jackson的...

    jackson-core-asl-1.9.13+jackson-mapper-asl-1.9.13札包

    在SSH(Spring、Struts、Hibernate)框架的集成应用中,Jackson库经常被用作数据交换的工具,特别是在Spring MVC中,它可以作为视图解析器,将Java对象转换为JSON响应返回给客户端。例如,当开发RESTful API时,使用...

    jackson2.6 jar包(3个包)

    - **序列化配置**:`ObjectMapper`提供了丰富的配置选项,如设置日期格式、忽略空值、自定义类型转换器等,以满足不同需求。 - **注解使用**:使用Jackson注解可以自定义序列化和反序列化的行为,例如`@JsonIgnore`...

    jackson-2.8.11.jar

    这些注解如`@JsonProperty`、`@JsonInclude`、`@JsonCreator`等,使得开发者无需编写繁琐的转换代码,只需在模型类上添加适当的注解,Jackson就能自动处理数据的转换。 其次,`jackson-core`模块是Jackson框架的...

    jackson2.x

    同时,Jackson还支持自定义序列化器和反序列化器,通过`@JsonSerialize`和`@JsonDeserialize`注解,可以实现更复杂的转换逻辑。 Jackson的性能优秀,兼容性广,支持Java 8特性,并且有大量社区支持和持续的更新,...

    jackson所需jar包springmvc中稳定版

    确保在项目中正确引入这些jar包,并配置Spring MVC以使用Jackson作为默认的消息转换器,通常需要在`web.xml`或Spring配置文件中添加相关配置。例如,添加以下代码片段可以启用Jackson作为HTTP消息转换器: ```xml ...

    使用jackson完成json与java对象的互相转换实例

    对于复杂的类型转换,可以定义`JsonSerializer`和`JsonDeserializer`,或者使用`@JsonDeserialize`和`@JsonSerialize`注解指定自定义的转换器。 5. **配置和性能优化** `ObjectMapper`有许多配置选项,如日期格式...

    springboot-jackson-auto-transform-enum.zip

    Jackson自定义序列化和反序列化是提高灵活性和控制JSON转换过程的关键功能。当涉及到枚举类型(enum)时,这种定制尤其重要,因为默认的序列化方式可能不满足所有业务需求。 1. **Jackson库**:Jackson是Java领域最...

    《Jackson 框架,轻易转换JSON》学习笔记

    - 自定义序列化器和反序列化器:通过实现`JsonSerializer`和`JsonDeserializer`接口,可以自定义特定类型的数据转换规则。 - JSON View:通过定义视图,可以在序列化时选择暴露哪些属性。 - 模式匹配:使用`@...

    jackson-annotations-2.2.3,jackson-core-2.2.3,jackson-databind-2.2.3

    - 集合和Map的处理:Jackson可以自动处理List、Set、Map等集合类型,也可以自定义转换规则。 总的来说,Jackson是一个强大且灵活的库,能够处理各种JSON操作,广泛应用于RESTful服务、Web应用、微服务等场景。了解...

Global site tag (gtag.js) - Google Analytics