0

I have an object, which I would like my jackson to serialize. For instance:

 public class RaceCar {
    public String model;
    public Int topSpeed;
}

My difficulty is that I do not want all of my RaceCar's fields to be serialized. I have attempted to cast my object to a superclass which does not not have access to the fields that I want to hide. For instance:

    public class Car {
       public String model;
    }

However, despite the cast, jackson still manages to serialize all of my RaceCar's fields. The output would be:

{"model": "x103", "topSpeed": 200}

Jackson serializes all of my RaceCar's fields even when the RaceCar object is cast to Object. I am guessing that jackson uses some sort of relfection mechanism to bypass my cast. Is there anyway to prevent jackson from bypassing my cast?

Edit: I should have specified that I can not use @JsonIgnore, because in some cases I would like to return the entire object and in others, I would like to return the object with less fields.

Dipen
  • 536
  • 2
  • 5
  • 13
  • 1
    [reading the documentation would be a good place to start next time](https://github.com/FasterXML/jackson-docs) –  Jun 26 '16 at 01:47

1 Answers1

1

MixIn is what you need:

Q38034525.java

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

public class Q38034525
{
    public static void main(String[] args) throws Exception
    {
        final RaceCar rc = new RaceCar();
        rc.model = "Corvette Stringray";
        rc.topSpeed = 195;

        final ObjectMapper om = new ObjectMapper();
        System.out.println(om.writeValueAsString(rc));
        final ObjectMapper om2 = om.copy().addMixIn(RaceCar.class, RestrictedRaceCar.class);
        System.out.println(om2.writeValueAsString(rc));
    }

    public static abstract class RestrictedRaceCar
    {
        @JsonIgnore
        public Integer topSpeed;
    }

    public static class RaceCar
    {
        public String model;
        public Integer topSpeed;
    }
}

Outputs:

{"model":"Corvette Stringray","topSpeed":195}
{"model":"Corvette Stringray"}

Note:

You must .copy() or create a new instance of ObjectMapper as they are immutable and just doing .addMixIn() on the instance will not modify it.