1

I want to parse multiple yaml files and add a print them on a table. I have the code to parse the yaml, but I am trying to figure out a way to add a property to the class (if not available).

Below is my code

public void readyml() throws JsonParseException, JsonMappingException, IOException{
        
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    mapper.findAndRegisterModules();

    Order order = mapper.readValue(new File("src/main/resources/orderInput.yaml"), Order.class);
    
    System.out.println("order ::: " + order);
    
}

the above code reads src/main/resources/orderInput.yaml

orderNo: A001
date: 2019-04-17
customerName: Customer, Joe
orderLines:
    - item: No. 9 Sprockets
      quantity: 12
      unitPrice: 1.23
    - item: Widget (10mm)
      quantity: 4
      unitPrice: 3.45

maps them to the Order and OrderList classes, and prints the values

My problem is, incase there is a new property added to the yaml, I want my code to pick it up

Can you please help

Saurabh Jhunjhunwala
  • 2,832
  • 3
  • 29
  • 57
  • technically the same as: https://stackoverflow.com/questions/3127189/java-classes-with-dynamic-fields – Lino Feb 16 '21 at 12:49
  • While Jackson internally uses SnakeYAML, please tag the API *you* are using, which is Jackson's. I corrected the tags. – flyx Feb 16 '21 at 13:01

1 Answers1

-1

Modified the code to map the attributes to a map, instead of a class

public void readyml() throws JsonParseException, JsonMappingException, IOException{
        
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    mapper.findAndRegisterModules();

    Map<String,Object> dynamicProperties = new HashMap<String,Object>();
        
    dynamicProperties = mapper.readValue(new File("src/main/resources/orderInput.yaml"), Map.class);
        
    System.out.println("order ::: " + dynamicProperties);
    
}
Saurabh Jhunjhunwala
  • 2,832
  • 3
  • 29
  • 57