Last updated: December 8, 2021
Written by: Eugen Paraschiv
- Data
- Jackson
- Jackson Basics
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 :)
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.
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
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.
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.
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
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
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
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
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
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
Do JSON right with Jackson
Download theE-book
Get the most out of the Apache HTTP Client
Download theE-book
Get Started with Apache Maven:
Download the E-book
Working on getting your persistence layer right with Spring?
Explore theeBook
Building a REST API with Spring?
Download the E-book
Get started with Spring and Spring Boot, through the LearnSpring course:
>> LEARNSPRING
Explore Spring Boot 3 and Spring 6 in-depth through building afull REST API with the framework:
>>The New “REST With Spring Boot”
Get started with Spring and Spring Boot, through the referenceLearn Spring course:
>> LEARNSPRING
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.