Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement Custom Parameter Converter in springboot by jackson

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you how jackson implements custom parameter converters in springboot. I hope you will get something after reading this article. Let's discuss it together.

Springboot jackson use-Custom Parameter Converter

Jackson is used by default in springboot, and many parameter converters are implemented, including EnumToStringConverter and StringToEnumConverterFactory, for interconversion of strings and enumerations. However, it is converted to each other according to the enumeration name.

Functions to be implemented

Null attribute I don't want to convert to a json string

Date object I want to convert to the specified format

I have multiple enumerations, such as public enum ChannelWayEnum {Bluetooth (0, "Bluetooth"), NB (1, "NB-IOT"), G4 (2, "self-built 4G"), Ali (3, "ali-4G");}, which cannot be converted with the default converter. A custom transformation is required.

Train of thought

Override the default injected ObjectMapper and implement objectMapper by yourself. You can set the null field to be ignored

Customize the Converter for date objects

Enumeration needs to implement interface IEnum, and then customize the converter for the IEnum interface

Key code

Inject ObjectMapper

@ Configurationpublic class JacksonConfig {@ Bean public ObjectMapper objectMapper () {return createObjectMapper ();} private ObjectMapper createObjectMapper () {ObjectMapper objectMapper = new ObjectMapper (); SimpleModule simpleModule = new SimpleModule (); / * serialization: object = > jsonString * / simpleModule.addSerializer (WashEnum.class, new WashEnumSerializer ()); simpleModule.addSerializer (IEnum.class, new EnumSerializer ()) SimpleModule.addSerializer (Date.class, new DateSerializer ()); simpleModule.addSerializer (Boolean.class, new BooleanSerializer ()); / / ignore null field objectMapper.setSerializationInclusion (JsonInclude.Include.NON_NULL) / * deserialization: jsonString= > object * / / allows json attribute names not to use double quotes objectMapper.configure (JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); / / ignores non-existent fields objectMapper.configure (DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); simpleModule.addDeserializer (String.class, new StringDeserializer ()) SimpleModule.addDeserializer (Date.class, new DateDeserializer ()); simpleModule.addDeserializer (WashEnum.class, new WashEnumDeserializer ()); simpleModule.addDeserializer (Enum.class, new EnumDeserializer ()); / / deserialized enumeration, simpleModule.addDeserializer (Boolean.class, new BooleanDeserializer ()); objectMapper.registerModule (simpleModule); return objectMapper;}}

Conversion of date object

@ JsonComponentpublic class DateDeserializer extends JsonDeserializer implements Converter {@ Override public Date deserialize (JsonParser p, DeserializationContext ctxt) {try {return convert (p.getText ());} catch (IOException e) {e.printStackTrace ();} return null;} @ Override public Date convert (String source) {if (StringUtil.isBlank (source)) {return null } return TimeUtil.toDate (TimeUtil.str2Time (source, TimeFormat.DEFAULT));}} @ JsonComponentpublic class DateSerializer extends JsonSerializer implements Converter {@ Override public void serialize (Date value, JsonGenerator gen, SerializerProvider serializers) {try {gen.writeString (convert (value));} catch (IOException e) {e.printStackTrace () @ Override public String convert (Date source) {return TimeUtil.time2Str (TimeUtil.date2Time (source), TimeFormat.DEFAULT);}}

Interface

/ * * all enumerations inherit this interface. * @ param enumerates the data type of the actual value * / public interface IEnum {/ / enumerates the actual value V getValue (); static T getBean (String value,Class tClass) {if (StringUtil.isBlank (value)) {return null } for (T enumObj: tClass.getEnumConstants ()) {if (value.equals (enumObj.getValue (). ToString () {return enumObj;}} return null;} default String getStr () {return String.valueOf (getValue ());}}

Enumerated converter

/ * json= > object * / @ JsonComponentpublic class EnumDeserializer extends JsonDeserializer implements ContextualDeserializer {private Class targetClass = null; public EnumDeserializer () {} public EnumDeserializer (Class targetClass) {this.targetClass = targetClass;} @ Override public T deserialize (JsonParser p, DeserializationContext ctxt) {/ / if (targetClassclass.isAssignableFrom (targetClass)) {try {return IEnum.getBean (p.getText (), targetClass) } catch (IOException e) {e.printStackTrace ();} /} return null;} @ Override public JsonDeserializer createContextual (DeserializationContext ctxt, BeanProperty property) {Class targetClass = (Class) ctxt.getContextualType () .getRawClass (); return new EnumDeserializer (targetClass) }} / * serialize the enum enumeration to json * @ author chenzy * @ since 2019.12.19 * / @ JsonComponentpublic class EnumSerializer extends JsonSerializer {@ Override public void serialize (T value, JsonGenerator gen, SerializerProvider serializers) throws IOException {Optional data = Optional.of (value); if (data.isPresent ()) {/ / non-empty gen.writeObject (data.get (). GetValue ()) } else {/ / gen.writeString ("");}

Here is the real converter.

/ * IEnum= > str * / @ Componentpublic class Enum2StrConverter 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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report