简体   繁体   中英

Jackson - JsonTypeInfo, property that can handles both camel and snake case

Is there a way, thru Jackson annotation to specify the property in JsonTypeInfo to handle both camel and snake case? For example, the following would only handle the case for proper serialization of JSON string that uses snake-case. Is there a way to handle both serialization and deserialization thru annotation? I am all ears for other suggestion as well. Thanks!

@JsonTypeInfo(
  use = Id.NAME,
  include = As.EXISTING_PROPERTY,
  property = "data_type",
  visible = true,
  defaultImpl = ActionDataImpl.class)
@JsonSubTypes(value = {
  @JsonSubTypes.Type(value = LogActionDataImpl.class, name = "LogActionData")
})
public interface IActionData {

  @JsonProperty("data_type")
  String getDataType();

  String getNumber();

  String getFoo();
}

My solution is to creates one more interface that is used as mixin, particularly when I am expecting fields naming using snake-case.

@JsonTypeInfo(
  use = Id.NAME,
  include = As.EXISTING_PROPERTY,
  property = "dataType",
  visible = true,
  defaultImpl = ActionDataImpl.class)
@JsonSubTypes(value = {
  @JsonSubTypes.Type(value = LogActionDataImpl.class, name = "LogActionData")
})
public interface IActionData {

  String getDataType();

  String getNumber();

  String getFoo();
}

@JsonTypeInfo(
  use = Id.NAME,
  include = As.EXISTING_PROPERTY,
  property = "data_type",
  visible = true,
  defaultImpl = ActionDataImpl.class)
@JsonSubTypes(value = {
  @JsonSubTypes.Type(value = LogActionDataImpl.class, name = "LogActionData")
})
public interface IActionDataSnakeCase extends IActionData {
}

When creating an snake-case object mapper, I would do this.

final ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
objectMapper.addMixIn(IActionData.class, IActionDataSnakeCase.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM