Friday, 14 January 2022

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

No comments:

Post a Comment