Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Jackson: @JsonAutoDetect: customize visibility semantics for serialization

@JsonAutoDetect annotation is used to customize the Visibility semantics for data serialization.

For example, below snippet enables the serialization of private properties.



'JsonAutoDetect.Visibility' is an enumeration for possible visibility thresholds that can be used to limit which methods and fields are auto-detected. Below table summarizes the possible visibility levels.

Visibility constant

Description

ANY

all kinds of access Modifiers from private to public are acceptable.

NON_PRIVATE

Value that means that any other access modifier other than 'private' is considered auto-detectable.

PROTECTED_AND_PUBLIC

Value that means access modifiers 'protected' and 'public' are auto-detectable (and 'private' and "package access" == no modifiers are not)

PUBLIC_ONLY

Value to indicate that only 'public' access modifier is considered auto-detectable.

NONE

Value that indicates that no access modifiers are auto-detectable. this can be used to explicitly disable auto-detection for specified types.

DEFAULT

Value that indicates that default visibility level (whatever it is, depends on context) is to be used. This usually means that inherited value (from parent visibility settings) is to be used.

Find the below working application.

PrivateModel.java

package com.sample.app.model;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;

@JsonAutoDetect(fieldVisibility = Visibility.ANY)
public class PrivateModel {
private int x;
private int y;

public PrivateModel(int x, int y) {
this.x = x;
this.y = y;
}

}

CustomizeVisibility.java

package com.sample.app.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sample.app.model.PrivateModel;

public class CustomizeVisibility {
public static void main(String[] args) throws JsonProcessingException {

PrivateModel obj = new PrivateModel(10, 12);
String result = new ObjectMapper().writeValueAsString(obj);

System.out.println(result);
}
}

Output

{"x":10,"y":12}



Previous                                                    Next                                                    Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Jackson: @JsonAutoDetect: customize visibility semantics for serialization

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×