下面列出了怎么用com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public final VisibilityChecker<?> getDefaultVisibilityChecker()
{
VisibilityChecker<?> vchecker = _configOverrides.getDefaultVisibility();
// then global overrides (disabling)
// 05-Mar-2018, tatu: As per [databind#1947], need to see if any disabled
if ((_mapperFeatures & AUTO_DETECT_MASK) != AUTO_DETECT_MASK) {
if (!isEnabled(MapperFeature.AUTO_DETECT_FIELDS)) {
vchecker = vchecker.withFieldVisibility(Visibility.NONE);
}
if (!isEnabled(MapperFeature.AUTO_DETECT_GETTERS)) {
vchecker = vchecker.withGetterVisibility(Visibility.NONE);
}
if (!isEnabled(MapperFeature.AUTO_DETECT_IS_GETTERS)) {
vchecker = vchecker.withIsGetterVisibility(Visibility.NONE);
}
if (!isEnabled(MapperFeature.AUTO_DETECT_SETTERS)) {
vchecker = vchecker.withSetterVisibility(Visibility.NONE);
}
if (!isEnabled(MapperFeature.AUTO_DETECT_CREATORS)) {
vchecker = vchecker.withCreatorVisibility(Visibility.NONE);
}
}
return vchecker;
}
/**
* Constructor that will assign given visibility value for all
* properties.
*
* @param v level to use for all property types
*/
public Std(Visibility v)
{
// typically we shouldn't get this value; but let's handle it if we do:
if (v == Visibility.DEFAULT) {
_getterMinLevel = DEFAULT._getterMinLevel;
_isGetterMinLevel = DEFAULT._isGetterMinLevel;
_setterMinLevel = DEFAULT._setterMinLevel;
_creatorMinLevel = DEFAULT._creatorMinLevel;
_fieldMinLevel = DEFAULT._fieldMinLevel;
} else {
_getterMinLevel = v;
_isGetterMinLevel = v;
_setterMinLevel = v;
_creatorMinLevel = v;
_fieldMinLevel = v;
}
}
@Override
public Std withVisibility(PropertyAccessor method, Visibility v)
{
switch (method) {
case GETTER:
return withGetterVisibility(v);
case SETTER:
return withSetterVisibility(v);
case CREATOR:
return withCreatorVisibility(v);
case FIELD:
return withFieldVisibility(v);
case IS_GETTER:
return withIsGetterVisibility(v);
case ALL:
return with(v);
//case NONE:
default:
// break;
return this;
}
}
/**
* json序列化
*
* @return
*/
@Bean
public RedisSerializer<Object> jackson2JsonRedisSerializer() {
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
//objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL, As.WRAPPER_ARRAY);
serializer.setObjectMapper(objectMapper);
return serializer;
}
public void testAutoDetectDisable() throws IOException
{
ObjectMapper mapper = getJaxbMapper();
Jackson183Bean bean = new Jackson183Bean();
Map<String,Object> result;
// Ok: by default, should see 2 fields:
result = writeAndMap(mapper, bean);
assertEquals(2, result.size());
assertEquals("a", result.get("a"));
assertEquals("b", result.get("b"));
// But when disabling auto-detection, just one
mapper = getJaxbMapperBuilder()
.changeDefaultVisibility(vc -> vc.withVisibility(PropertyAccessor.GETTER, Visibility.NONE))
.build();
result = writeAndMap(mapper, bean);
assertEquals(1, result.size());
assertNull(result.get("a"));
assertEquals("b", result.get("b"));
}
/**
* Reads a JSON manifest file into a JSON manifest object.
*
* @param jsonManifestFile the JSON manifest file.
*
* @return the manifest object.
* @throws java.io.IOException if any errors were encountered reading the JSON file.
* @throws IllegalArgumentException if the manifest file has validation errors.
*/
public M readJsonManifest(File jsonManifestFile) throws IOException, IllegalArgumentException
{
// Verify that the file exists and can be read.
HerdFileUtils.verifyFileExistsAndReadable(jsonManifestFile);
// Deserialize the JSON manifest.
BufferedInputStream buffer = new BufferedInputStream(new FileInputStream(jsonManifestFile));
BufferedReader reader = new BufferedReader(new InputStreamReader(buffer, Charsets.UTF_8));
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
objectMapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.SETTER, Visibility.NONE);
M manifest = getManifestFromReader(reader, objectMapper);
// Validate the manifest and return it.
validateManifest(manifest);
return manifest;
}
public JsonMapper(ObjectMapper objectMapper, Include include, boolean fieldVisibility){
objectMapper.setSerializationInclusion(include);
// objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
// setDateFormat(DateUtils.DATE_TIME);
objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.configure(Feature.ALLOW_COMMENTS, true);
// objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
if(fieldVisibility)
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
objectMapper.setFilterProvider(filterProvider);
// objectMapper.addMixIn(target, mixinSource);
this.objectMapper = objectMapper;
this.typeFactory = this.objectMapper.getTypeFactory();
}
private static void doGoodMapper(ArrayList<AnInterface> childs)
throws JsonProcessingException {
ObjectMapper theGoodMapper = new ObjectMapper();
theGoodMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
theGoodMapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE);
theGoodMapper.setVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE);
theGoodMapper.setVisibility(PropertyAccessor.SETTER, Visibility.NONE);
theGoodMapper.setVisibility(PropertyAccessor.CREATOR, Visibility.NONE);
theGoodMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
String theJsonText = theGoodMapper.writeValueAsString(childs);
System.out.println(theJsonText);
try {
ArrayList<AnInterface> reconstructedChilds = theGoodMapper.readValue(
theJsonText, new TypeReference<ArrayList<AnInterface>>() {
});
System.out.println("The good mapper works ! ");
System.out.println(reconstructedChilds);
} catch (IOException e) {
System.err.println("Bad mapper fails " + e.getMessage());
}
}
private static void doBadMapper(ArrayList<AnInterface> childs)
throws JsonProcessingException {
ObjectMapper theBadMapper = new ObjectMapper();
theBadMapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE);
theBadMapper.setVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE);
theBadMapper.setVisibility(PropertyAccessor.SETTER, Visibility.NONE);
theBadMapper.setVisibility(PropertyAccessor.CREATOR, Visibility.NONE);
theBadMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
String theJsonText = theBadMapper.writeValueAsString(childs);
System.out.println(theJsonText);
try {
ArrayList<AnInterface> reconstructedChilds = theBadMapper.readValue(
theJsonText, new TypeReference<ArrayList<AnInterface>>() {
});
System.out.println(reconstructedChilds);
} catch (IOException e) {
System.err.println("Bad mapper fails " + e.getMessage());
}
}
private static boolean isSetterAutoDetected( RebindConfiguration configuration, PropertyAccessors propertyAccessors, BeanInfo info ) {
if ( !propertyAccessors.getSetter().isPresent() ) {
return false;
}
for ( Class<? extends Annotation> annotation : AUTO_DISCOVERY_ANNOTATIONS ) {
if ( propertyAccessors.isAnnotationPresentOnSetter( annotation ) ) {
return true;
}
}
JMethod setter = propertyAccessors.getSetter().get();
String methodName = setter.getName();
if ( !methodName.startsWith( "set" ) || methodName.length() <= 3 ) {
// no annotation on method and the method does not follow naming convention
return false;
}
JsonAutoDetect.Visibility visibility = info.getSetterVisibility();
if ( Visibility.DEFAULT == visibility ) {
visibility = configuration.getDefaultSetterVisibility();
}
return isAutoDetected( visibility, setter.isPrivate(), setter.isProtected(), setter.isPublic(), setter
.isDefaultAccess() );
}
private static boolean isFieldAutoDetected( RebindConfiguration configuration, PropertyAccessors propertyAccessors, BeanInfo info ) {
if ( !propertyAccessors.getField().isPresent() ) {
return false;
}
for ( Class<? extends Annotation> annotation : AUTO_DISCOVERY_ANNOTATIONS ) {
if ( propertyAccessors.isAnnotationPresentOnField( annotation ) ) {
return true;
}
}
JField field = propertyAccessors.getField().get();
JsonAutoDetect.Visibility visibility = info.getFieldVisibility();
if ( Visibility.DEFAULT == visibility ) {
visibility = configuration.getDefaultFieldVisibility();
}
return isAutoDetected( visibility, field.isPrivate(), field.isProtected(), field.isPublic(), field
.isDefaultAccess() );
}
private static boolean isAutoDetected( JsonAutoDetect.Visibility visibility, boolean isPrivate, boolean isProtected, boolean
isPublic, boolean isDefaultAccess ) {
switch ( visibility ) {
case ANY:
return true;
case NONE:
return false;
case NON_PRIVATE:
return !isPrivate;
case PROTECTED_AND_PUBLIC:
return isProtected || isPublic;
case PUBLIC_ONLY:
case DEFAULT:
return isPublic;
default:
return false;
}
}
/**
* Constructor that allows directly specifying minimum visibility levels to use
*/
public Std(Visibility getter, Visibility isGetter, Visibility setter,
Visibility creator, Visibility field)
{
_getterMinLevel = getter;
_isGetterMinLevel = isGetter;
_setterMinLevel = setter;
_creatorMinLevel = creator;
_fieldMinLevel = field;
}
protected Std _with(Visibility g, Visibility isG, Visibility s,
Visibility cr, Visibility f) {
if ((g == _getterMinLevel)
&& (isG == _isGetterMinLevel)
&& (s == _setterMinLevel)
&& (cr == _creatorMinLevel)
&& (f == _fieldMinLevel)
) {
return this;
}
return new Std(g, isG, s, cr, f);
}
@Override
public Std with(Visibility v)
{
if (v == Visibility.DEFAULT) {
return DEFAULT;
}
return new Std(v);
}
private void initializeObjectMapper() {
objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
// make sure that the object mapper stores type information when serializing objects
objectMapper.enableDefaultTyping();
}
private void initializeObjectMapper() {
objectMapper = new ObjectMapper();
// make sure that the object mapper sees all fields
objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
// make sure that the object mapper stores type information when serializing objects
objectMapper.enableDefaultTyping();
}
public String writeValueAsString(Object obj) {
ObjectMapper json = new ObjectMapper();
json.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
try {
return json.writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Bean
@Primary
public ObjectMapper objectMapper() {
return new ObjectMapper() //
.setVisibility(PropertyAccessor.FIELD, Visibility.PUBLIC_ONLY)
.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) //
.registerModule(new Jdk8Module()) //
.registerModule(new ParameterNamesModule());
}
@Override
public void configureJacksonObjectMapper(ObjectMapper objectMapper) {
objectMapper.setVisibility(objectMapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(Visibility.ANY)
.withGetterVisibility(Visibility.NONE)
.withIsGetterVisibility(Visibility.NONE));
}
@Override
public void evaluate(DelegateExecution execution) {
Object value = this.transformation.getValue(execution);
VariableTypes variableTypes = CommandContextUtil.getVariableServiceConfiguration().getVariableTypes();
try {
variableTypes.findVariableType(value);
} catch (final FlowableException e) {
// Couldn't find a variable type that is able to serialize the output value
// Perhaps the output value is a Java bean, we try to convert it as JSon
try {
final ObjectMapper mapper = new ObjectMapper();
// By default, Jackson serializes only public fields, we force to use all fields of the Java Bean
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
// By default, Jackson serializes java.util.Date as timestamp, we force ISO-8601
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));
value = mapper.convertValue(value, JsonNode.class);
} catch (final IllegalArgumentException e1) {
throw new FlowableException("An error occurs converting output value as JSon", e1);
}
}
execution.setVariable(this.getTarget(), value);
}
public JsonCodec(boolean indent, boolean privateVisible){
objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
if(indent){
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
}
if(privateVisible){
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
objectMapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE);
}
}
public FieldObjectMapper() {
// only pay attention to fields
setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
setVisibility(PropertyAccessor.GETTER, Visibility.NONE);
setVisibility(PropertyAccessor.SETTER, Visibility.NONE);
setVisibility(PropertyAccessor.CREATOR, Visibility.NONE);
setVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE);
// ignore unknown fields when reading
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// ignore null fields when writing
setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
public ObjectMapper getContext(Class<?> cls) {
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.SETTER, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
mapper.setVisibility(PropertyAccessor.CREATOR, Visibility.ANY);
mapper.registerModule(new UriSchemeModule());
return mapper;
}
private static ObjectMapper createObjectMapper() {
SimpleModule module = new SimpleModule()
.addKeySerializer(NodeResolution.class, new NodeResolutionSerializer())
.addDeserializer(NodeResolution.class, new NodeResolutionDeserializer());
return new ObjectMapper()
.registerModule(module)
.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE)
.setSerializationInclusion(Include.NON_EMPTY)
.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
}
protected void init(ObjectMapper objectMapper) {
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.setVisibility(objectMapper.getSerializationConfig()
.getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.enable(Feature.WRITE_BIGDECIMAL_AS_PLAIN);
objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
objectMapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
objectMapper.addMixIn(Throwable.class, ThrowableMixIn.class);
}
public ObjectMapper getObjectMapper() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
// try without pretty print..all data in single line
return mapper
.setPropertyNamingStrategy(
new SearchFieldsLowerCaseNameStrategy())
.setVisibility(PropertyAccessor.FIELD, Visibility.ANY)
.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
private ObjectMapper getObjectMapper() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
// try without pretty print..all data in single line
return mapper
.setPropertyNamingStrategy(
new SearchFieldsLowerCaseNameStrategy())
.setVisibility(PropertyAccessor.FIELD, Visibility.ANY)
// .setPropertyNamingStrategy(
// new SearchPropertyNameCaseInsensitiveNameStrategy())
.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
/**
* @param mapper
* @param annotationsToUse
*/
public JacksonProvider(ObjectMapper mapper, Annotations[] annotationsToUse) {
super(mapper, annotationsToUse);
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.GETTER, Visibility.PROTECTED_AND_PUBLIC);
mapper.setVisibility(PropertyAccessor.SETTER, Visibility.PROTECTED_AND_PUBLIC);
mapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true);
mapper.setPropertyNamingStrategy(getPropertyNamingStrategy());
}
/**
* @param mapper
* @param annotationsToUse
*/
public JacksonProvider(ObjectMapper mapper, Annotations[] annotationsToUse) {
super(mapper, annotationsToUse);
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.GETTER, Visibility.PROTECTED_AND_PUBLIC);
mapper.setVisibility(PropertyAccessor.SETTER, Visibility.PROTECTED_AND_PUBLIC);
mapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true);
mapper.setPropertyNamingStrategy(getPropertyNamingStrategy());
}