How to Manage Jackson Library Class Serialization

I have a class (let's call it Piece) containing a type member com.jme3.math.ColorRGBA. With default serialization Jackson member is serialized, not only as its members r, g, band a, but also with the use of getters type getAlpha.

Since this is clearly redundant, I would like to control serialization and serialize only those primary elements. Are there any annotations I can write to my class to control the serialization of members with types that are not under my control, or for some custom serializers?

Perhaps I can write my own serializer for the class Piece, although rather than the multitasking ColorRGBA serializer, the default serialization is great for all other properties Piece, so I would like to configure how little is possible.

I do not want to change the source of the library jme3, the solution must be implemented outside the class ColorRGBA.

+4
source share
3 answers

You can use mixin to make sure the class is serialized according to your needs. Consider the following:

// The source class (where you do not own the source code)
public class ColorRGBA {
    public float a; // <-- Want to skip this one
    public float b;
    public float g;
    public float r;
}

Then create a mixin where you ignore the property a.

// Create a mixin where you ignore the "a" property
@JsonIgnoreProperties("a")
public abstract class RGBMixin {
    // Other settings if required such as @JsonProperty on abstract methods.
}

Finally, configure your mapper using mixin:

ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(ColorRGBA.class, RGBMixin.class);
System.out.println(mapper.writeValueAsString(new ColorRGBA()));

The output will be:

{ "": 0,0, "": 0.0, "": 0,0}

, ObjectMapper.addMixInAnnotations Jackson 2.5 :

mapper.addMixIn(ColorRGBA.class, RGBMixin.class);

JavaDocs

+12

A

, :

@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
public class ColorRGBA {

B

:

ObjectMapper mapper = new ObjectMapper();
mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));

mapper.writeValue(stream, yourObject);

C

VisibilityChecker .

+1

, :

@JsonSerialize(using = CustomColorRGBASerializer.class)
ColorRGBA color;

See also this answer on how to serialize the Date field .

0
source

All Articles