Today, I messed around with Jackson, that Java library for handling JSON. I wanted to see how easily I could convert a Java object to JSON and back.
Setting Up
First, I grabbed the Jackson library. I used Maven, ’cause it’s what I usually use. I just added the dependency to my file, like so:
*.core
jackson-databind
2.13.3
You can put these in the dependency section in your file. I just replaced the version number to the one I needed. The jackson-databind one has all the stuff for converting objects.
Creating a Simple Class
Then, I made a super basic Java class. I called it Person, with just a couple of fields:
public class Person {
private String name;
private int age;
//Need these for Jackson
public Person() {}
public Person(String name, int age) {
* = name;
* = age;
public String getName() {
return name;
public void setName(String name) {
* = name;
public int getAge() {
return age;
public void setAge(int age) {
* = age;
See? Nothing fancy. Just a name and age. I also added an empty constructor, and getters and setters, because that’s kind of a requirement for Jackson to do its thing.
Object to JSON
Next, I wrote some code to turn a Person object into a JSON string. That’s where the ObjectMapper comes in:
import *.*;
public class Main {
public static void main(String[] args) throws Exception{
ObjectMapper mapper = new ObjectMapper();
Person person = new Person("Bob", 30);
String jsonString = *(person);
*(jsonString);
I created an ObjectMapper, made a Person object, and then used writeValueAsString(). That gave me the JSON string, and I printed to the console.
My output printed is:
{"name":"Bob","age":30}
JSON to Object
Going the other way, from JSON back to a Person object, was just as simple:
import *.*;
public class Main {
public static void main(String[] args) throws Exception{
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{"name":"Alice","age":25}";
Person person = *(jsonString, *);
*("Name: " + *() + ", Age: " + *());
This time, I used readValue(). I gave it the JSON string and told it what class to create (). Then printed out the name and age from the new Person object to verify whether working fine.
My output printed is:
Name: Alice, Age: 25
Wrapping Up
And that’s it! It’s pretty straightforward to convert object and JSON by using Jackson. I didn’t do anything too complex, but it seems like a handy library for dealing with JSON in Java. I might try some more advanced stuff later, like custom serialization or handling different data formats.