Change field case with an ObjectMapper

前端 未结 4 830
伪装坚强ぢ
伪装坚强ぢ 2020-12-30 02:24

I think I need to create a specialist ObjectMapper and cannot find any sample code to start the process.

The creator of the JSON is using .Net

相关标签:
4条回答
  • 2020-12-30 02:36

    Your first issue can be addressed very simply with the @JsonProperty annotation:

    // java-side class
    public class Facet
    {
        @JsonProperty("Name")
        public String name;
    
        @JsonProperty("Value")
        public String value;
    }
    

    Now the ObjectMapper will match up the differently-cased field names. If you don't want to add annotations into your classes, you can create a Mix-in class to stand in for your Facet:

    public class FacetMixIn
    {
        @JsonProperty("Name")
        public String name;
    
        @JsonProperty("Value")
        public String value;
    }
    
    objectMapper.getDeserializationConfig().addMixInAnnotations(Facet.class, FacetMixIn.class);
    

    This will achieve the same thing, without requiring additional annotations in your Facet class.

    0 讨论(0)
  • 2020-12-30 02:39

    This problem could be solved from Jackson 2.5.0 like this:

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    

    From the javadoc:

    com.fasterxml.jackson.databind.MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES

    Feature that will allow for more forgiving deserialization of incoming JSON. If enabled, the bean properties will be matched using their lower-case equivalents, meaning that any case-combination (incoming and matching names are canonicalized by lower-casing) should work.

    Note that there is additional performance overhead since incoming property names need to be lower-cased before comparison, for cases where there are upper-case letters. Overhead for names that are already lower-case should be negligible however.

    Feature is disabled by default.

    Since: 2.5

    0 讨论(0)
  • 2020-12-30 02:40

    Just a quick update as I was looking for same answer and a code snippet objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

    0 讨论(0)
  • 2020-12-30 02:45

    Instead of annotating each field, the Jackson ObjectMapper can be configured to use a built-in or custom PropertyNamingStrategy, to apply a consistent translation between Java property/field names and JSON element names.

    For example:

    myObjectMapper.setPropertyNamingStrategy(PascalCaseStrategy);
    
    0 讨论(0)
提交回复
热议问题