Deserialize property file that contains dot with Jackson

◇◆丶佛笑我妖孽 提交于 2020-01-23 11:52:54

问题


In our application we are trying to read a flat property file using Jackson to match the properties to our POJO Everything works fine, but when the property name contains some dot, the wholo POJO is set to null

Here is a sample of the property file

p.test=Just a test

Here is my POJO

public class BasicPOJO {

  @JsonProperty("p.test")
  private String test;

  public String getTest() {
    return test;
  }

  public void setTest(String test) {
    this.test = test;
  }
}

And here is how I map it

InputStream in = ApplicationProperties.class.getClassLoader()
    .getResourceAsStream("application.properties");

JavaPropsMapper mapper = new JavaPropsMapper();

try {
  BasicPOJO myProperties =  mapper.readValue(in,
      BasicPOJO .class);

  LOGGER.debug("Loaded properties {}", myProperties); //myProperties.test is null here

} catch (IOException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
}

Any help will be appreciated


回答1:


Dot in property names is used to represent nested objects. This is described here https://github.com/FasterXML/jackson-dataformats-text/blob/master/properties/README.md#basics-of-conversion

Since default java.util.Properties can read "flat" key/value entries in, what is the big deal here?

Most properties files actually use an implied structure by using a naming convention; most commonly by using period ('.') as logical path separator.

You can disable it by using JavaPropsSchema.withoutPathSeparator() as described here https://github.com/FasterXML/jackson-dataformats-text/blob/master/properties/README.md#javapropsschemapathseparator

JavaPropsSchema schema = JavaPropsSchema.emptySchema()
    .withoutPathSeparator();
BasicPOJO myProperties = mapper.readerFor(BasicPOJO.class)
    .with(schema)
    .readValue(source);


来源:https://stackoverflow.com/questions/48871920/deserialize-property-file-that-contains-dot-with-jackson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!