The source code is for testing only and should not be used commercially. The source code comes from the Internet. If there is any infringement, please contact me to remove it.
JSON类库Jackson优雅序列化Java枚举类

1. preface

inJavaIn order to avoid too many magic values during development, we used enumeration classes to encapsulate some static state code. However, returning the meaning of these enumerations correctly and comprehensively to the front end is not so smooth. We usually use theJacksonClass library serialization objects areJSONToday, let's talk about usingJacksonUniversal techniques for serialized enumerations.

2. universal enumeration normal form

In order to facilitate unified processing and standardize a unified style, it is recommended to specify a unified abstract interface, such as:

/**
 * The interface Enumerator.
 */
public interface Enumerator {
    /**
     * Code integer.
     *
     * @return the integer
     */
    Integer code();

    /**
     * Description string.
     *
     * @return the string
     */
    String description();
}

Let's write an implementation to identify gender:

public enum GenderEnum implements Enumerator {

    UNKNOWN(0, "Unknown"),

    MALE(1, "Male"),

    FEMALE(2, "Female");


    private final Integer code;
    private final String description;

    GenderEnum(Integer code, String description) {
        this.code = code;
        this.description = description;
    }


    @Override
    public Integer code() {
        return code;
    }

    @Override
    public String description() {
        return description;
    }
}

3. serialized enumeration

If we use it directlyJacksonSerializing an enumeration will only simply output the enumeratedStringName:

    @Resource
    private ObjectMapper objectMapper;

    @Test
    void enumTest() {
        try {
            String s = objectMapper.writeValueAsString(GenderEnum.MALE);
            //Output string MALE
            System.out.println(s);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

We expect toGenderEnum.MALE serialized as {"code":1,"description":"male"} 。we can askObjectMapperCustomize oneModuleTo achieve this personalized need:

         //Declare a simple Module object
         SimpleModule module = new SimpleModule();
           //Add a serializer to the Module
            module.addSerializer(Enumerator.class, new JsonSerializer<Enumerator>() {
                @Override
                public void serialize(Enumerator value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                   //Start writing object
                    gen.writeStartObject();
                    //Specify k v respectively   code   description 
                    gen.writeNumberField("code",value.code());
                    gen.writeStringField("description",value.description());
                    //Explicit end operation
                    gen.writeEndObject();
                }
            });

        //Register Module
        objectMapper.registerModule(module);

Then executing it again will get the results we expect. However, this is not reasonable.

4. Automatic global configuration in Spring Boot

inSpring BootIn the application, we want to configure it globally.Spring BootAutomatic configuration of provides us with a personalized customizationObjectMapperOf the possibilities, you just need to declare oneJackson2ObjectMapperBuilderCustomizerand injectSpring IoC:

@Bean
public Jackson2ObjectMapperBuilderCustomizer enumCustomizer(){
    return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.serializerByType(Enumerator.class, new JsonSerializer<Enumerator>() {
        @Override
        public void serialize(Enumerator value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                    gen.writeStartObject();
                    gen.writeNumberField("code",value.code());
                    gen.writeStringField("description",value.description());
                    gen.writeEndObject();


        }
    });
}

This achieves global configuration.

5. summary

Here we introduce how to customizeJacksonLibrary for the purpose of more friendly serialization of enumerations. In fact, not just enumerating, you can also implement other serialization, deserialization, and customization of time output formats.

read more
Resource download
PriceFree
The use is limited to testing, experiments, and research purposes. It is prohibited for all commercial operations. This team is not responsible for any illegal behavior of users during use. Please self-test all source codes! There is no guarantee of the integrity and validity of your source code. All source code is collected from the entire network
Original link:https://bcbccb.cn/en/4627.html, please indicate the source for reprinting. Disclaimer: This resource has not been authorized by the original rights holder and is not commercially available. It can only be used to learn and analyze the underlying code, CSS, etc., and is prohibited for commercial purposes. Any relevant disputes and legal liabilities arising from unauthorized commercial use shall be fully borne by the user. Everyone is responsible to support genuine copies. Please delete them within 24 hours after downloading. Thank you for your support!
1

Comments0

五星棋牌广西地方玩法 柳州麻将_来宾麻将_南宁麻将
Five-star chess Guangxi local play Liuzhou Mahjong_Guest Mahjong_Nanning Mahjong
Someone bought it 8 minutes ago Go and have a look

Site Announcements

The source code (theme/plug-in/application source code) and other resources provided by this site are only for learning and exchange

Commercial use is prohibited, otherwise all consequences will be borne by the downloading user!

Some resources are collected or copied online. If they infringe on your legitimate rights and interests, please write to us.

Currently, members have a big reward, and the current price for a lifetime member is 299 gold coins.Recent price adjustments

Join quickly, opportunities wait for no one! immediately participated in

Captcha

Fast login to social accounts

en_USEnglish