Feature: PropertyNamingStrategy

(see Jira entry JACKSON-178 for details)

Problem

Some services use naming conventions that are different from Java Bean naming convention. For example, instead of:

  {
    "inReplyToUserId" : "abc123"
  }

Twitter API serves something looking like:

  {
    "in_reply_to_user_id" : "abc123"
  }

now, to map this to Java beans, one would either have to use POJO definition like:

  public interface {
    public String getin_reply_to_user_id();
  }

or use annotations:

  public interface {
    @JsonProperty("in_reply_to_user_id")
    public String getInReplyToUserId();
  }

neither of which approach is all that good: one is pretty ugly (unreadable), other lots of additional work to decorate all getters.

Solution

Jackson 1.8 adds new abstraction, PropertyNamingStrategy, which makes it possible to change way logical POJO property names are mapping to physical JSON property names. By implement custom implementation and registering it with ObjectMapper, you could solve above problem like so:

  class MyBean {
     private String inReply;
     public void setInReplyToUserId(String s) { inReply = s; }
     public String getInReplyToUserId() { return inReply; }
  }

  class MyNaming extends PropertyNamingStrategy {
    @Override
    public String nameForGetterMethod(MapperConfig<?> config,
         AnnotatedMethod method, String defaultName)
    {
      // Replace underscore+letter with upper-case(letter)
      // (left as exercise to reader!)
      return convertName(defaultName);
    }
  }

  objectMapper.setPropertyNamingStrategy(new MyNaming());
  // and serialize, deserialize values as 

which changes what JSON properties are considered to map POJO properties, as per custom name conversion.


CategoryJackson

JacksonFeaturePropertyNamingStrategy (last edited 2011-03-09 07:02:16 by TatuSaloranta)

Copyright ©2009 FasterXML, LLC