DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Jackson vs Gson: Edge Cases in JSON Parsing for Java Apps
  • The Configure() Method in Jackson in JSON
  • Easy Mapping JSON to Java Objects Using Jackson

Trending

  • Start Coding With Google Cloud Workstations
  • Simplify Authorization in Ruby on Rails With the Power of Pundit Gem
  • Why Rate Limiting Matters in Istio and How to Implement It
  • Platform Engineering for Cloud Teams

Jackson Mixin to the Rescue

See how you can use Jackson Mixin to serialize and deserialize third-party classes, keep your code base clean, and work in a more modular way.

By 
Mohammad Nadeem user avatar
Mohammad Nadeem
·
Sep. 28, 16 · Tutorial
Likes (14)
Comment
Save
Tweet
Share
109.6K Views

Join the DZone community and get the full member experience.

Join For Free

Many-a-times it's not possible to annotate classes with Jackson Annotations simply for serialization/deserialization needs. There could be many reasons, for example:

  • Classes that need to be serialized/deserialized are third-party classes.
  • You don’t want Jackson invading your code base everywhere.
  • You want cleaner and more modular design.

Jackson Mixin would help solve above the problems easily. Let's consider an example:

Let’s say you want to serialize/deserialize following class (Note that it does not have getter/setter)

public class Address {

    private String city;
    private String state;

        public Address(String city, String state) {
        this.city = city;
        this.state = state;;
    }

    @Override
    public String toString() {
        return "Address [city=" + city + ", state=" + state +  "]";
    }
}

If you try to serialize, you would get the following error:

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class com.some.package.Address and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )

To solve the above issue, you have to do the following:

  1. Add a default constructor.
  2. Add getter/setter for each property.

However, that is not possible for many cases. Here, we can use Jackson Mixin to get around this problem. To do that, we have to create corresponding mixing class, as can be seen here, constructor should match as that of your source object and you have to use Jackson annotations (@JsonCreator, @JsonProperty etc.)

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public abstract class AddressMixin {

    @JsonCreator
    public AddressMixin(
            @JsonProperty("city") String city,
            @JsonProperty("state") String state) {
        System.out.println("Wont be called");

    }
}

Still, you will get the following exception

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class com.some.package.Address and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )

It turns out that we have to tell Jackson to use reflection and access the fields.

mapper.setVisibility(mapper.getSerializationConfig()
        .getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));

Here is the test code:

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonMixInTest {

    public static void main(String[] args) throws IOException {

        Address address = new Address("Hyderabad",  "Telangana");

        ObjectMapper mapper = buildMapper();

        final String json = mapper.writeValueAsString(address);
        System.out.println(json);

        mapper.addMixIn(Address.class, AddressMixin.class);

        final Address deserializedUser = mapper.readValue(json, Address.class);
        System.out.println(deserializedUser);
    }

private static ObjectMapper buildMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(mapper.getSerializationConfig()
    .getDefaultVisibilityChecker()
    .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
    .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
    .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
    .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
    return mapper;
    }
}

Here is the output:

{"city":"Hyderabad","state":"Telangana"}
Address [city=Hyderabad, state=Telangana]

 References

  • Jackson Issue 

Jackson (API)

Published at DZone with permission of Mohammad Nadeem, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Jackson vs Gson: Edge Cases in JSON Parsing for Java Apps
  • The Configure() Method in Jackson in JSON
  • Easy Mapping JSON to Java Objects Using Jackson

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!