Main Tutorials

How to map a subset of a JSON file using Jackson

This article shows how to map a subset of a JSON file using Jackson.

Table of contents:

P.S Tested with Jackson 2.17.0

1. Download Jackson

Declare jackson-databind in the pom.xml.

pom.xml

  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.17.0</version>
  </dependency>

2. Map a subset of a JSON file

Review the JSON string below. We only need the activities array, specifically the start, end, and content fields of each activity; we want to ignore the location and observations fields.

resources/jackson/subset.json

{
  "model": {
    "activities": [
      {
        "start": "2014-05-05T18:10:50.000",
        "end": "2014-05-05T18:17:30.000",
        "content": "PrepareHotTea",
        "location": "Malaysia",
        "observations": []
      }
    ]
  }
}

3. Define Java Classes that reflect JSON structure

To map a subset of a JSON file using Jackson, we can define a Java class structure that reflects only the parts of the JSON we’re interested in. Later, we will configure Jackson to ignore the rest of the JSON content that doesn’t have corresponding fields in the Java class.

We need a Java class to represent the structure of the JSON string; here, we create classes for Model and Activity.

ModelWrapper.java

package com.mkyong.json.jackson.subset;

import java.util.List;

public class ModelWrapper {
    private Model model;

    public Model getModel() {
        return model;
    }

    public void setModel(Model model) {
        this.model = model;
    }

    public static class Model {
        private List<Activity> activities;

        public List<Activity> getActivities() {
            return activities;
        }

        public void setActivities(List<Activity> activities) {
            this.activities = activities;
        }
    }

    public static class Activity {
        private String start;
        private String end;
        private String content;

        public String getStart() {
            return start;
        }

        public void setStart(String start) {
            this.start = start;
        }

        public String getEnd() {
            return end;
        }

        public void setEnd(String end) {
            this.end = end;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }
}

4. Ignoring Unneeded Fields with Jackson

Jackson defaults to prompting an error for JSON fields that do not have corresponding fields in the Java classes. In this example, both the location and observations fields will hit the error.

We can configure the ObjectMapper to tell Jackson to ignore any JSON fields that do not have corresponding fields in the Java classes. Jackson will ignore the location and observations fields in this example.


  ObjectMapper mapper = new ObjectMapper();
  // Configure ObjectMapper to ignore unknown properties
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

5. Testing the subset of JSON using Jackson

SubsetJsonExample.java

package com.mkyong.json.jackson.subset;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.InputStream;

public class SubsetJsonExample {

    public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();
        // Configure ObjectMapper to ignore unknown properties
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        // Get file content from resources folder.
        try (InputStream inputStream = SubsetJsonExample.class.
                getClassLoader().getResourceAsStream("jackson/subset.json")) {

            // map JSON to Java object
            ModelWrapper modelWrapper = mapper.readValue(inputStream, ModelWrapper.class);

            for (ModelWrapper.Activity activity : modelWrapper.getModel().getActivities()) {
                System.out.println("Activity Start: " + activity.getStart());
                System.out.println("Activity End: " + activity.getEnd());
                System.out.println("Activity Content: " + activity.getContent());
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}

Output


Activity Start: 2014-05-05T18:10:50.000
Activity End: 2014-05-05T18:17:30.000
Activity Content: PrepareHotTea

6. Download Source Code

$ git clone https://github.com/mkyong/java-json

$ cd jackson/subset

7. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments