Jackson Serialize Field to Different Name

后端 未结 2 1872
-上瘾入骨i
-上瘾入骨i 2021-01-05 13:35

I have this JSON to deserialize:

{
    \"first-name\": \"Alpha\",
    \"last-name\": \"Beta\",
    \"gender\": \"m\"
}

I want to serialize

2条回答
  •  长情又很酷
    2021-01-05 14:24

    There is a far easier way to do this - create an objectmapper that uses the "addMixin" function.

    Class to be serialized:

    Class YouWantToSerializeMe {
    
        public String firstName;
        public String lastName;
        public String gender;
    
        @JsonProperty("firstName")
        public String getFirstNameCC() {
            return firstName;
        }
    
        @JsonProperty("lastName")
        public String getLastNameCC() {
        return lastName;
        }
    }
    

    Now, to serialize using both the built-in field names and custom field names, you can do this:

    Class DoTheSerializing {
    
        String serializeNormally(YouWantToSerializeMe me) {
             ObjectMapper objectMapper = new ObjectMapper();
             ObjectWriter objectWriter = objectMapper.writer();
    
             return objectWriter(me)
         }
    
        String serializeWithMixin(YouWantToSerializeMe me) {
             ObjectMapper objectMapper = new ObjectMapper();
             ObjectWriter objectWriter = objectMapper
                     .addMixIn(YouWantToSerializeMe.class, MyMixin.class)
                     .writer();
    
             return objectWriter(me)
        }
    
        interface MyMixin {
    
             @JsonProperty("first-name")
             public String getFirstNameCC();
    
             @JsonProperty("last-name")
             public String getLastNameCC();
        }    
    
    }
    

    This uses an embedded interface in the class to keep things very local. You can make lots of optimizations around this, such as creating a static ObjectMapper and loading/unloading the mixin.

    Using the interface as a "template" to control the mapping function is really powerful. You can add things at both the field and class level.

提交回复
热议问题