Mr. Nicky
Mr. Nicky

Reputation: 1659

Jackson ObjectMapper read value into particular Java object

I need to deserialize a yml file into a Java object which does not have a default constructor. This causes Jackson's ObjectMapper to complain and throw an exception.

The Java class in particular is not my own (it's a dependency), so I cannot modify it. The author's idea for the class is to construct objects using the Builder Pattern and has not provided a default constructor.

In order to circumvent the issue I would need to create an adapter class, I suppose. Then I would build my object by using the serialized adapter object and filling in the builder.

Is there any cleaner way to do this? If only ObjectMapper provided methods to read from a stream into a specific object, I could make an empty object using the builder and then fill it up with Jackson...

Upvotes: 1

Views: 1777

Answers (2)

Mr. Nicky
Mr. Nicky

Reputation: 1659

Okay, so what I ended up doing is I loaded up the YAML file into Jackson's ObjectMapper. Then I traversed the resulting JsonNode object which represents the whole structure of the YAML file and then generically passed in the parameters to the builder class.

Upvotes: 0

DwB
DwB

Reputation: 38300

This is just an expanded version of the @Steve11235 comment.

This is not an adaptor, it is just a workaround.

  1. Create a class that matches the JSON format; I will call this Blammy.
  2. Include a method in the Blammy class to populate the Builder for the desired actual class; I will call this Blammy.builderate(DesiredBuilder)
  3. Use jackson to deserialize the JSON into the Blammy class.
  4. Post deserialization, create the desired Builder and pass it to the Blammy.builderate() method.

Upvotes: 1

Related Questions