TIL: Loading YAML With Jackson
Wanted to use a YAML file for some config settings in a new app I’m writing, so I needed to look up how to do so in Java. Lots of people pointed to using Jackson for doing the loading, which seems to be the defacto when doing json reading as well.
The first thing that I found while doing this was that the process is much much much more involved than simply reading in files in other languages.
With both of my background languages, python and JavaScript, you’d simply load the file, use a library to send the file too, and then get an object out of it. It was that easy to just load up a file with your config settings in it.
Using Jackson is similar to this… only that you need to take the extra step of actually defining out that data model before you can deserialize it. I guess that makes sense in Java world, as everything revolves around objects, but it’s still just weird to me that all of that has to be defined beforehand…
So you need to create that data model ahead of time, with your getters and setters.
Much of what I’m going to be writing about here came from this guide I found while seaching around.
Adding dependencies to maven
We need to add Jackson to our project:
|
|
Creating our YAML file
Going to keep is super basic. We’ll just create a file with basic login info
|
|
Define Our Model
We need to define the data model for the login details that are in our YAML file. As mentioned above, this will be our fields plus getters and setters.
|
|
Load our file
The last thing to do is to do the loading of the data into the model:
|
|
And then you’re good to use any values that you loaded in as needed via getters/setters.
💚