JSON to Java Objects: Parsing with Jackson and Gson

Introduction

JSON (JavaScript Object Notation) is a widely used data format for data exchange on the web. Often, you’ll need to parse JSON data received from an API or file and convert it into Java objects to work with it in your application. This tutorial will cover how to achieve this using two popular Java libraries: Jackson and Gson. Both libraries offer powerful and flexible solutions for JSON parsing and object mapping.

Understanding the Problem

Let’s consider a typical JSON structure:

{
  "libraryname": "My Library",
  "mymusic": [
    {
      "Artist Name": "Aaron",
      "Song Name": "Beautiful"
    },
    {
      "Artist Name": "Britney",
      "Song Name": "Oops I did It Again"
    },
    {
      "Artist Name": "Britney",
      "Song Name": "Stronger"
    }
  ]
}

Our goal is to convert this JSON string into Java objects that allow us to easily access the data, for instance, myobj.libraryname to retrieve "My Library" or myobj.mymusic[0].artistName to get "Aaron".

Parsing with Jackson

Jackson is a high-performance Java library specifically designed for processing JSON.

Approach 1: Using Maps and Lists

Jackson can directly parse the JSON into Java Map and List objects. This is a simple, albeit less type-safe, approach.

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
import java.util.List;

public class JsonJacksonMap {
    public static void main(String[] args) throws Exception {
        String jsonString = "{\n" +
                "  \"libraryname\": \"My Library\",\n" +
                "  \"mymusic\": [\n" +
                "    {\n" +
                "      \"Artist Name\": \"Aaron\",\n" +
                "      \"Song Name\": \"Beautiful\"\n" +
                "    },\n" +
                "    {\n" +
                "      \"Artist Name\": \"Britney\",\n" +
                "      \"Song Name\": \"Oops I did It Again\"\n" +
                "    },\n" +
                "    {\n" +
                "      \"Artist Name\": \"Britney\",\n" +
                "      \"Song Name\": \"Stronger\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> map = mapper.readValue(jsonString, Map.class);

        String libraryName = (String) map.get("libraryname");
        List<Map<String, String>> songs = (List<Map<String, String>>) map.get("mymusic");

        System.out.println("Library Name: " + libraryName);
        System.out.println("First Song Artist: " + songs.get(0).get("Artist Name"));
    }
}

Approach 2: Creating Java Classes

A more structured and type-safe approach is to define Java classes that mirror the JSON structure. This allows you to directly map the JSON data to objects of these classes.

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;

// Define the Java classes
class Library {
    @JsonProperty("libraryname")
    public String name;

    @JsonProperty("mymusic")
    public List<Song> songs;
}

class Song {
    @JsonProperty("Artist Name")
    public String artistName;

    @JsonProperty("Song Name")
    public String songName;
}

public class JsonJacksonClasses {
    public static void main(String[] args) throws Exception {
        String jsonString = "{\n" +
                "  \"libraryname\": \"My Library\",\n" +
                "  \"mymusic\": [\n" +
                "    {\n" +
                "      \"Artist Name\": \"Aaron\",\n" +
                "      \"Song Name\": \"Beautiful\"\n" +
                "    },\n" +
                "    {\n" +
                "      \"Artist Name\": \"Britney\",\n" +
                "      \"Song Name\": \"Oops I did It Again\"\n" +
                "    },\n" +
                "    {\n" +
                "      \"Artist Name\": \"Britney\",\n" +
                "      \"Song Name\": \"Stronger\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        ObjectMapper mapper = new ObjectMapper();
        Library library = mapper.readValue(jsonString, Library.class);

        System.out.println("Library Name: " + library.name);
        System.out.println("First Song Artist: " + library.songs.get(0).artistName);
    }
}

The @JsonProperty annotation allows you to map JSON field names to different Java field names if necessary.

Parsing with Gson

Gson, developed by Google, is another popular Java library for converting Java objects to JSON and vice versa.

import com.google.gson.Gson;
import java.util.List;

// Define the Java classes (same as before)
class Library {
    public String name;
    public List<Song> songs;
}

class Song {
    public String artistName;
    public String songName;
}

public class JsonGson {
    public static void main(String[] args) {
        String jsonString = "{\n" +
                "  \"libraryname\": \"My Library\",\n" +
                "  \"mymusic\": [\n" +
                "    {\n" +
                "      \"Artist Name\": \"Aaron\",\n" +
                "      \"Song Name\": \"Beautiful\"\n" +
                "    },\n" +
                "    {\n" +
                "      \"Artist Name\": \"Britney\",\n" +
                "      \"Song Name\": \"Oops I did It Again\"\n" +
                "    },\n" +
                "    {\n" +
                "      \"Artist Name\": \"Britney\",\n" +
                "      \"Song Name\": \"Stronger\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        Gson gson = new Gson();
        Library library = gson.fromJson(jsonString, Library.class);

        System.out.println("Library Name: " + library.name);
        System.out.println("First Song Artist: " + library.songs.get(0).artistName);
    }
}

Choosing Between Jackson and Gson

Both Jackson and Gson are excellent choices.

  • Jackson is generally considered more performant and offers more advanced features for customization.
  • Gson is known for its simplicity and ease of use, making it a good choice for smaller projects or when rapid development is a priority.

Leave a Reply

Your email address will not be published. Required fields are marked *