4

I have a property.yml file in my project, as follows:

propertyA : "valueA"
propertyB: "valueB"
propertyC: "valueC"

I am using the following java code for deserialization from the above yml file:

File configFile = new File(classLoader.getResource("property.yml".getFile());
ObjectMapper yamlMapper = new ObjectMapper(new YAMLFactory());
config = yamlMapper.readValue(configFile, MyPOJO.class);

Now, I need to write unit tests. My code has a validation that if any of the propertyA, propertyB and propertyC is missing in the yml file, the code should throw an exception.

Is there a way I can ask the mapper to ignore certain fields during deserialization (assuming that is absent in property.yml) and perform my testing?

property.yml actually contains huge no. of properties(= n, say). It is not feasible to generate n property.yml files for testing, whereas in each of them, one property would be missing.

Arijit
  • 420
  • 7
  • 14

3 Answers3

0

You can use @JsonIgnoreProperties(ignoreUnknown = true) on the class level.

Jayesh Choudhary
  • 748
  • 2
  • 12
  • 30
  • 2
    I want that the mapper, for example, ignores propertyA even though it is present in the yml file. What you said would help only when propertyA is not present in the yml file and we still want the deserialization to pass. – Arijit Jan 01 '18 at 17:34
  • I think for that you can use **@JsonIgnore ** over the field which you want to ignore. This will not read that field from Json. – Jayesh Choudhary Jan 02 '18 at 11:47
  • Thanks, but that will be done on the POJO, and would cause the mappers to ignore the fields each and every time. I want to ignore only propertyA in iteration 1, only propertyB in iteration 2 and so on. Can I put something in the mapper itself which does not affect the POJO? – Arijit Jan 02 '18 at 12:00
  • If this is the case then you need to use different properties file or you need to create separate Json for each iteration. Because there is no other option. – Jayesh Choudhary Jan 02 '18 at 12:13
  • Hmm, I think creating n different properties file will not be feasible for my case. – Arijit Jan 02 '18 at 13:14
0

You should configure the deserialzer not to fail on unknown property:

File configFile = new File(classLoader.getResource("property.yml".getFile());
ObjectMapper yamlMapper = new ObjectMapper(new YAMLFactory())
    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
config = yamlMapper.readValue(configFile, MyPOJO.class);
Mistriel
  • 459
  • 4
  • 9
-1

I had a similar issue, the solution is 'setSerializationInclusion' property of ObjectMapper can be used as:

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.writeValue(new File(System.getProperty("user.dir") + "properties.yml"), manifestPojo);

This will write only non-null values to an output YAML file.

Roham Rafii
  • 2,929
  • 7
  • 35
  • 49