Jackson Unmarshalling JSON with Unknown Properties | Baeldung (2024)

Last updated: December 8, 2021

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (1)

Written by: Eugen Paraschiv

  • Data
  • Jackson
  • Jackson Basics

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (2)

It's finally here:

>> The Road toMembership and Baeldung Pro.

Going into ads, no-ads reading, and bit about howBaeldung works if you're curious :)

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (3)

Azure Container Apps is a fully managed serverless containerservice that enables you to build and deploy modern,cloud-native Java applications and microservices at scale. Itoffers a simplified developer experience while providing theflexibility and portability of containers.

Of course, Azure Container Apps has really solid support for ourecosystem, from a number of build options, managed Java components,native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visitthe documentationpage.

You can also ask questions and leave feedback on the AzureContainer Apps GitHub page.

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (4)

Java applications have a notoriously slow startup and a longwarmup time. The CRaC (Coordinated Restore at Checkpoint)project from OpenJDK can help improve these issues by creating acheckpoint with an application's peak performance and restoringan instance of the JVM to that point.

To take full advantage of this feature, BellSoft providescontainers that are highly optimized for Java applications. Thesepackage Alpaquita Linux (a full-featured OS optimized for Java andcloud environment) and Liberica JDK (an open-source Java runtimebased on OpenJDK).

These ready-to-use images allow us to easily integrate CRaCin a Spring Boot application:

Improve Javaapplication performance with CRaC support

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (5)

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a 14-DayFree Trial of Orkes Conductor today.

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (6)

Azure Container Apps is a fully managed serverless containerservice that enables you to build and deploy modern,cloud-native Java applications and microservices at scale. Itoffers a simplified developer experience while providing theflexibility and portability of containers.

Of course, Azure Container Apps has really solid support for ourecosystem, from a number of build options, managed Java components,native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, youcan get started over on the documentation page.

And, you can also ask questions and leave feedback on the AzureContainer Apps GitHub page.

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (7)

Whether you're just starting out or have years of experience,Spring Boot is obviously a great choice for building a webapplication.

Jmix builds on this highly powerful and mature Boot stack,allowing devs to build and deliver full-stack webapplications without having to code the frontend. Quiteflexibly as well, from simple web GUI CRUD applications to complexenterprise solutions.

Concretely, The Jmix Platform includes a framework builton top of Spring Boot, JPA, and Vaadin, and comes with JmixStudio, an IntelliJ IDEA plugin equipped with a suite ofdeveloper productivity tools.

The platform comes with interconnected out-of-the-boxadd-ons for report generation, BPM, maps, instant web appgeneration from a DB, and quite a bit more:

>> Become an efficientfull-stack developer with Jmix

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (8)

DbSchema is a super-flexible database designer, which cantake you from designing the DB with your team all the way tosafely deploying the schema.

The way it does all of that is by using a design model, adatabase-independent image of the schema, which can be shared in ateam using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you tointeract with the database using diagrams, visually composequeries, explore the data, generate random data, import data orbuild HTML5 database reports.

>>Take a look at DBSchema

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (9)

Get non-trivial analysis (and trivial, too!) suggested rightinside your IDE or Git platform so you can code smart, createmore value, and stay confident when you push.

Get CodiumAI for free and become part of a community ofover 280,000 developers who are already experiencing improved andquicker coding.

Write code that works the way you meant it to:

>>CodiumAI. Meaningful Code Tests for Busy Devs

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (10)

The AI Assistant to boost Boost your productivity writing unittests - Machinet AI.

AI is all the rage these days, but for very good reason. Thehighly practical coding companion, you'll get the power ofAI-assisted coding and automated unit test generation.
Machinet's Unit Test AI Agent utilizes your own projectcontext to create meaningful unit tests that intelligently alignswith the behavior of the code.
And, the AI Chat crafts code and fixes errors with ease,like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI:

>>Install Machinet AI in your IntelliJ

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (11)

DbSchema is a super-flexible database designer, which cantake you from designing the DB with your team all the way tosafely deploying the schema.

The way it does all of that is by using a design model, adatabase-independent image of the schema, which can be shared in ateam using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you tointeract with the database using diagrams, visually composequeries, explore the data, generate random data, import data orbuild HTML5 database reports.

>>Take a look at DBSchema

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (12)

Since its introduction in Java 8, the Stream API has become astaple of Java development. The basic operations like iterating,filtering, mapping sequences of elements are deceptively simple touse.

But these can also be overused and fall into some commonpitfalls.

To get a better understanding on how Streams work and howto combine them with other language features, check out our guideto Java Streams:

Download theE-book

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (13)

Do JSON right with Jackson

Download theE-book

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (14)

Get the most out of the Apache HTTP Client

Download theE-book

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (15)

Get Started with Apache Maven:

Download the E-book

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (16)

Working on getting your persistence layer right with Spring?

Explore theeBook

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (17)

Building a REST API with Spring?

Download the E-book

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (18)

Get started with Spring and Spring Boot, through the LearnSpring course:

>> LEARNSPRING

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (19)

Explore Spring Boot 3 and Spring 6 in-depth through building afull REST API with the framework:

>>The New “REST With Spring Boot”

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (20)

Get started with Spring and Spring Boot, through the referenceLearn Spring course:

>> LEARNSPRING

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (21)

Yes, Spring Security can be complex, from the more advancedfunctionality within the Core to the deep OAuth support in theframework.

I built the security material as two full courses - Core andOAuth, to get practical with these more complex scenarios. Weexplore when and how to use each feature and code through it onthe backing project.

You can explore the course here:

>> Learn SpringSecurity

1. Overview

In this tutorial, we’re going to take a look at the unmarshalling process with Jackson 2.x, specifically how to deal with JSON content with unknown properties.

To dig deeper and learn other cool things we can do with Jackson, we can check out the main Jackson tutorial.

Further reading:

Jackson Ignore Properties on Marshalling

Control your JSON Output - Ignore certain fields directly, by name or by type (with mixins) for Jackson bliss.

Read more

Jackson - Change Name of Field

Jackson - Change the name of a field to adhere to a specific JSON format.

Read more

2. Unmarshall a JSON With Additional/Unknown Fields

JSON input comes in all shapes and sizes, and most of the time, we need to map it to predefined Java objects with a set number of fields. The goal is to simply ignore any JSON properties that cannot be mapped to an existing Java field.

For example, say we need to unmarshal JSON to the following Java entity:

public class MyDto { private String stringValue; private int intValue; private boolean booleanValue; // standard constructor, getters and setters }

2.1. UnrecognizedPropertyException on Unknown Fields

Trying to unmarshala JSON with unknown properties to this simple Java Entity will lead to a com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:

@Test(expected = UnrecognizedPropertyException.class)public void givenJsonHasUnknownValues_whenDeserializingAJsonToAClass_thenExceptionIsThrown() throws JsonParseException, JsonMappingException, IOException { String jsonAsString = "{\"stringValue\":\"a\"," + "\"intValue\":1," + "\"booleanValue\":true," + "\"stringValue2\":\"something\"}"; ObjectMapper mapper = new ObjectMapper(); MyDto readValue = mapper.readValue(jsonAsString, MyDto.class); assertNotNull(readValue);}

This will fail with the following exception:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "stringValue2" (class org.baeldung.jackson.ignore.MyDto), not marked as ignorable (3 known properties: "stringValue", "booleanValue", "intValue"])

2.2. Dealing With Unknown Fields Using the ObjectMapper

We can now configure the full ObjectMapper to ignore unknown properties in the JSON:

new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

We should then be able to read this kind of JSON into a predefined Java entity:

@Testpublic void givenJsonHasUnknownValuesButJacksonIsIgnoringUnknownFields_whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException { String jsonAsString = "{\"stringValue\":\"a\"," + "\"intValue\":1," + "\"booleanValue\":true," + "\"stringValue2\":\"something\"}"; ObjectMapper mapper = new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); MyDto readValue = mapper.readValue(jsonAsString, MyDto.class); assertNotNull(readValue); assertThat(readValue.getStringValue(), equalTo("a")); assertThat(readValue.isBooleanValue(), equalTo(true)); assertThat(readValue.getIntValue(), equalTo(1));}

2.3. Dealing With Unknown Fields at the Class Level

We can also mark a single class as accepting unknown fields, instead of the entire Jackson ObjectMapper:

@JsonIgnoreProperties(ignoreUnknown = true)public class MyDtoIgnoreUnknown { ... }

Now we should be able to test the same behavior as before. The unknown fields are simply ignored, and only known fields are mapped:

@Testpublic void givenJsonHasUnknownValuesButUnknownFieldsAreIgnoredOnClass_whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException { String jsonAsString = "{\"stringValue\":\"a\"," + "\"intValue\":1," + "\"booleanValue\":true," + "\"stringValue2\":\"something\"}"; ObjectMapper mapper = new ObjectMapper(); MyDtoIgnoreUnknown readValue = mapper .readValue(jsonAsString, MyDtoIgnoreUnknown.class); assertNotNull(readValue); assertThat(readValue.getStringValue(), equalTo("a")); assertThat(readValue.isBooleanValue(), equalTo(true)); assertThat(readValue.getIntValue(), equalTo(1));}

3. Unmarshall an Incomplete JSON

Similar to additional unknown fields, unmarshalling an incomplete JSON, a JSON that doesn’t contain all the fields in the Java class, isn’t a problem with Jackson:

@Testpublic void givenNotAllFieldsHaveValuesInJson_whenDeserializingAJsonToAClass_thenCorrect() throws JsonParseException, JsonMappingException, IOException { String jsonAsString = "{"stringValue":"a","booleanValue":true}"; ObjectMapper mapper = new ObjectMapper(); MyDto readValue = mapper.readValue(jsonAsString, MyDto.class); assertNotNull(readValue); assertThat(readValue.getStringValue(), equalTo("a")); assertThat(readValue.isBooleanValue(), equalTo(true));}

4. Conclusion

In this article, we discussed deserializing a JSON with additional, unknown properties using Jackson.

This is one of the most common things to configure when working with Jackson, since we often need to map JSON results of external REST APIs to an internal Java representation of the entities of the API.

The implementation of all of these examples and code snippets can be found in my GitHub project.

Jackson Unmarshalling JSON with Unknown Properties | Baeldung (2024)
Top Articles
Cailey Fleming Feet
W 2 Formular Entschluesselung des W 2 Formulars Offenlegungen zur Sozialversicherungssteuer - FasterCapital
How To Use Scarabs Poe
1977 Hit For Elo Wsj Crossword Clue
Noaa 7 Day Tropical Outlook
Best Insulation for 2x4 and 2x6 Walls
Courses In Touch
Craigslist Ludington Michigan
Ynot Parking Visitors
Methodist Laborworkx
Allina Akn Network
Magicseaweed Capitola
205-293-6392
Ups Cc Center
Yumiiangell
Tom DiVecchio - LILLY BROADCASTING | LinkedIn
7 Best Dialysis Technician Resume Examples for 2024
Azpeople Self Service
Ultimate Guide to Visiting Dungeness, UK
Bambooee Divorce
Bulls set the ‘gold standard’
The Self Directed Learning and Assessment Route | CIMA
John Deere S100 Vs Cub Cadet Xt1
Tethrd Coupon Code The Hunting Public
Ridgid Pro Tool Storage System
The Autopsy Report: Overview, Suggested Autopsy Report Headings, An Overview of the Autopsy Report
24 Hour Supermarket Near Me Now
Jeep Österreich| Mopar | Vernetzte Dienste - Uconnect
Wenig Kooperation mit AfD auf kommunaler Ebene in Ostdeutschland
The Patch Bel Air
Honquest Obituaries
Recordpub Com Obits
Ben Leventhal Net Worth
Go.bryanisd.org Schoology Login
Crossword Help - Find Missing Letters & Solve Clues
Sanctuary 2022 Showtimes Near Santikos Entertainment Palladium
What is the Financial Ombudsman Service and how does it work?
0.03703 As A Fraction
Kaitlyn Krems Leak: The Truth Behind The Controversy
Understanding "X marks the spot" Idiom: Meaning, Origins & Usage - CrossIdiomas.com
Magicseaweed Encinitas
Paige Turco: Filme, Serien und Biografie
Doomz.io Unblocked Games 76
My Vidant Chart
Noaa Weather Forecast Pittsburgh
Log in or sign up to view
Taylor Cole: What Only True Fans Know About The Hallmark Star - The List
609-718-7432
Is Bankai Akuma Good
Puretalkusa.com/Amac
12 Rue Gotlib 21St Arrondissem*nt
Latest Posts
Article information

Author: Neely Ledner

Last Updated:

Views: 5923

Rating: 4.1 / 5 (62 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Neely Ledner

Birthday: 1998-06-09

Address: 443 Barrows Terrace, New Jodyberg, CO 57462-5329

Phone: +2433516856029

Job: Central Legal Facilitator

Hobby: Backpacking, Jogging, Magic, Driving, Macrame, Embroidery, Foraging

Introduction: My name is Neely Ledner, I am a bright, determined, beautiful, adventurous, adventurous, spotless, calm person who loves writing and wants to share my knowledge and understanding with you.