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).*

* An example annotation would be:*

*  @JsonDeserialize(using=MySerializer.class,*    as=MyHashMap.class,*    keyAs=MyHashKey.class,*    contentAs=MyHashValue.class*  )*
*

* Something to note on usage:*

    *
  • All other annotations regarding behavior during building should be on Builder*    class and NOT on target POJO class: for example @JsonIgnoreProperties should be on*    Builder to prevent "unknown property" errors.*  
  • *
  • Similarly configuration overrides (see {@link com.fasterxml.jackson.databind.ObjectMapper#configOverride})*    should be targeted at Builder class, not target POJO class.*  
  • *
**/ @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 propertiespublic Class 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 propertiespublic Class 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 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 propertiespublic Class 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 propertiespublic Class 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.*

* 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.*

* 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 {public static final SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");@Overridepublic 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 {public static final SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");@Overridepublic void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {jsonGenerator.writeString(format.format(date));}}


 
————————————————
版权声明:本文为CSDN博主「bandancer」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/bandancer/article/details/84926383


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部