private void addJsonTypeInfo(JDefinedClass klass, ObjectTypeDeclaration type) { if (!context.getConfig().isJacksonTypeInfo()) { return; } if (type.discriminator() == null) { return; } List<String> derivedTypes = context.getApiModel().findDerivedTypes(type.name()); if (derivedTypes.isEmpty()) { return; } JAnnotationUse typeInfo = klass.annotate(JsonTypeInfo.class); typeInfo.param("use", Id.NAME); typeInfo.param("include", As.EXISTING_PROPERTY); typeInfo.param("property", type.discriminator()); JAnnotationUse subTypes = klass.annotate(JsonSubTypes.class); JAnnotationArrayMember typeArray = subTypes.paramArray(VALUE); for (String derivedType : derivedTypes) { JDefinedClass subtype = pkg._getClass(derivedType); typeArray.annotate(Type.class).param(VALUE, subtype); } }
@Bean(name = "objectMapper") public ObjectMapper getObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new GuavaModule()); mapper.registerModule(new Jdk8Module()); mapper.registerModule(new JodaModule()); mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() { // borrowed from: http://jackson-users.ning.com/forum/topics/how-to-not-include-type-info-during-serialization-with @Override protected TypeResolverBuilder<?> _findTypeResolver(MapperConfig<?> config, Annotated ann, JavaType baseType) { // Don't serialize JsonTypeInfo Property includes if (ann.hasAnnotation(JsonTypeInfo.class) && ann.getAnnotation(JsonTypeInfo.class).include() == JsonTypeInfo.As.PROPERTY && SerializationConfig.class.isAssignableFrom(config.getClass())) { return null; } return super._findTypeResolver(config, ann, baseType); } }); return mapper; }
@RequestMapping("/") @ResponseBody public String home(@RequestParam(value = "name", defaultValue = "guest", required = false) String name) throws IOException { Random rand = new Random(); int id = rand.nextInt(); User webUser = new User(id, name); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(webUser); oos.close(); String webUserOISB64 = Base64.getEncoder().encodeToString(baos.toByteArray()); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY); String webUserJackson = objectMapper.writeValueAsString(webUser); String webUserJacksonB64 = Base64.getEncoder().encodeToString(webUserJackson.getBytes("utf-8")); return String.format("<a href='/?name=test'>set your name</a></br><a href='ois?sess=%s'>look at yourself</a></br><a href='jackson?sess=%s'>look at yourself</a>", webUserOISB64, webUserJacksonB64); }
@Override public void processSubTypeRule(TypeSpec.Builder typeSpec, TypeModel typeModel) { SubTypeModel subTypeModel = typeModel.getSubTypes(); AnnotationSpec typeInfoAnnotation = AnnotationSpec.builder(JsonTypeInfo.class) .addMember("use", "$L", "JsonTypeInfo.Id.NAME") .addMember("include", "$L", "JsonTypeInfo.As." + (subTypeModel.isExistingProperty() ? "EXISTING_PROPERTY" : "PROPERTY")) .addMember("property", "$S", subTypeModel.getProperty()) .build(); AnnotationSpec.Builder subTypesBuilder = AnnotationSpec.builder(JsonSubTypes.class); for (Map.Entry<String, String> subType : subTypeModel.getSubTypeMapping().entrySet()) { subTypesBuilder.addMember("value", "$L", AnnotationSpec.builder(JsonSubTypes.Type.class) .addMember("value", "$T.class", getClassName(subType.getValue())) .addMember("name", "$S", subType.getKey()) .build()); } typeSpec.addAnnotation(typeInfoAnnotation); typeSpec.addAnnotation(subTypesBuilder.build()); }
@SuppressWarnings("unchecked") private <S> Class<S> resolveJsonType(String path, Class<S> type) { JsonTypeInfo typeInfo = AnnotationUtils.findAnnotation(type, JsonTypeInfo.class); if (typeInfo == null) { return null; } String property = getPropertyName(typeInfo); String proppath = KvUtils.join(path, property); try { KvNode node = getStorage().get(proppath); if(node == null) { return null; } String str = node.getValue(); JsonSubTypes subTypes = AnnotationUtils.findAnnotation(type, JsonSubTypes.class); for (JsonSubTypes.Type t : subTypes.value()) { if (t.name().equals(str)) { return (Class<S>) t.value(); } } } catch (Exception e) { log.error("can't instantiate class", e); } return null; }
private void saveType(String path, T object, KeyValueStorage storage) { Class<?> clazz = object.getClass(); String name = PROP_TYPE; String value = clazz.getName(); JsonTypeInfo typeInfo = AnnotationUtils.findAnnotation(clazz, JsonTypeInfo.class); if (typeInfo != null && !clazz.equals(typeInfo.defaultImpl())) { JsonTypeInfo.As include = typeInfo.include(); if(include != JsonTypeInfo.As.PROPERTY && include != JsonTypeInfo.As.EXTERNAL_PROPERTY /* it for capability with jackson oddities */) { throw new IllegalArgumentException("On " + clazz + " mapping support only " + JsonTypeInfo.As.PROPERTY + " but find: " + include); } name = getPropertyName(typeInfo); value = getJsonType(clazz, typeInfo); } storage.set(KvUtils.join(path, name), value); }
protected void testRoot() { // while boundaries are compiler-checked, let's still verify superclass, as generics in Java are easy to bypass assertTrue("Invalid root type: " + expectedRoot, PolymorphicConfiguration.class.isAssignableFrom(expectedRoot)); JsonTypeInfo typeInfo = expectedRoot.getAnnotation(JsonTypeInfo.class); // TODO: test "property" and "use" values of the annotation assertNotNull("Root is not annotated with @JsonTypeInfo", typeInfo); if (expectedDefault != null) { assertTrue("Default type is not specified on root. Expected: " + expectedDefault.getName(), hasDefault(typeInfo)); assertEquals("Expected and actual default types are not the same", expectedDefault, typeInfo.defaultImpl()); } else { assertFalse("Expected no default type, but @JsonTypeInfo sets it to " + typeInfo.defaultImpl().getName() + ".", hasDefault(typeInfo)); } if (isConcrete(expectedRoot)) { JsonTypeName typeName = expectedRoot.getAnnotation(JsonTypeName.class); assertNotNull("Concrete root configuration type must be annotated with @JsonTypeName: " + expectedRoot.getName()); } }
/** * Connects to mmo server with hostname and port and login with given * username. * * @param host hostname or ip of server * @param port port to connect to * @param username login name */ public ServerConnection(String host, int port, String username) { this.host = host; this.port = port; this.username = username; mapper = new ObjectMapper().setDefaultTyping( new ObjectMapper.DefaultTypeResolverBuilder( ObjectMapper.DefaultTyping .OBJECT_AND_NON_CONCRETE) .init( JsonTypeInfo.Id.MINIMAL_CLASS, null) .inclusion(JsonTypeInfo.As.PROPERTY) .typeProperty("type") ) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .enable(SerializationFeature.INDENT_OUTPUT) .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); messageWriter = mapper.writerFor(Message.class); messageReader = mapper.reader(Message.class); }
/** * Configure an existing object mapper to work with Archie RM and AOM Objects. * Indentation is enabled. Feel free to disable again in your own code. * @param objectMapper */ public static void configureObjectMapper(ObjectMapper objectMapper) { objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.enable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); objectMapper.disable(SerializationFeature.WRITE_NULL_MAP_VALUES); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); objectMapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); //objectMapper. objectMapper.registerModule(new JavaTimeModule()); TypeResolverBuilder typeResolverBuilder = new ArchieTypeResolverBuilder() .init(JsonTypeInfo.Id.NAME, new OpenEHRTypeNaming()) .typeProperty("@type") .typeIdVisibility(true) .inclusion(JsonTypeInfo.As.PROPERTY); objectMapper.setDefaultTyping(typeResolverBuilder); }
private JsonTypeInfo getJsonTypeInfoAnnotation() { Class<?> tInspectedClass = this.getClass(); do { JsonTypeInfo tCheckedAnnotation = tInspectedClass .getAnnotation(JsonTypeInfo.class); if (tCheckedAnnotation != null) { return tCheckedAnnotation; } tInspectedClass = tInspectedClass.getSuperclass(); } while (tInspectedClass != null); return null; }
private String getJsonTypePropertyString() { Class<?> tInspectedClass = this.getClass(); do { JsonTypeInfo tJsonTypeInfoAnnotation = tInspectedClass .getAnnotation(JsonTypeInfo.class); if (tJsonTypeInfoAnnotation != null) { return tJsonTypeInfoAnnotation.property(); } tInspectedClass = tInspectedClass.getSuperclass(); } while (tInspectedClass != null); return null; }
@Override public void serializeWithType(JsonGenerator jgen, SerializerProvider provider, TypeSerializer typeSer) throws IOException, JsonProcessingException { // check if this class have JsonTypeInfo annotation JsonTypeInfo tJsonTypeInfoAnnotation = getJsonTypeInfoAnnotation(); if (tJsonTypeInfoAnnotation != null) { setFieldValue(DealField.useCustomField(tJsonTypeInfoAnnotation .property()), this.getClass().getName()); jgen.writeTree(mBeanRootNode); deleteField(DealField.useCustomField(tJsonTypeInfoAnnotation .property())); } else { jgen.writeTree(mBeanRootNode); } }
private static ImmutableMap<JClassType, String> extractMetadata( TreeLogger logger, RebindConfiguration configuration, JClassType type, Optional<JsonTypeInfo> jsonTypeInfo, Optional<JsonSubTypes> propertySubTypes, Optional<JsonSubTypes> typeSubTypes, ImmutableList<JClassType> allSubtypes ) throws UnableToCompleteException { ImmutableMap.Builder<JClassType, String> classToMetadata = ImmutableMap.builder(); classToMetadata.put( type, extractTypeMetadata( logger, configuration, type, type, jsonTypeInfo .get(), propertySubTypes, typeSubTypes, allSubtypes ) ); for ( JClassType subtype : allSubtypes ) { classToMetadata.put( subtype, extractTypeMetadata( logger, configuration, type, subtype, jsonTypeInfo .get(), propertySubTypes, typeSubTypes, allSubtypes ) ); } return classToMetadata.build(); }
public TypeSerializer buildTypeSerializer(SerializationConfig config, JavaType baseType, Collection<NamedType> subtypes) { if (_idType == JsonTypeInfo.Id.NONE) { return null; } TypeIdResolver idRes = idResolver(config, baseType, subtypes, true, false); switch (_includeAs) { case WRAPPER_ARRAY: return new AsArrayTypeSerializer(idRes, null); case PROPERTY: return new AsPropertyTypeSerializer(idRes, null, _typeProperty); case WRAPPER_OBJECT: return new AsWrapperTypeSerializer(idRes, null); case EXTERNAL_PROPERTY: return new AsExternalTypeSerializer(idRes, null, _typeProperty); } throw new IllegalStateException("Do not know how to construct standard type serializer for inclusion type: "+_includeAs); }
public TypeDeserializer buildTypeDeserializer(DeserializationConfig config, JavaType baseType, Collection<NamedType> subtypes) { if (_idType == JsonTypeInfo.Id.NONE) { return null; } TypeIdResolver idRes = idResolver(config, baseType, subtypes, false, true); // First, method for converting type info to type id: switch (_includeAs) { case WRAPPER_ARRAY: return new AsArrayTypeDeserializer(baseType, idRes, _typeProperty, _typeIdVisible, _defaultImpl); case PROPERTY: return new AsPropertyTypeDeserializer(baseType, idRes, _typeProperty, _typeIdVisible, _defaultImpl); case WRAPPER_OBJECT: return new AsWrapperTypeDeserializer(baseType, idRes, _typeProperty, _typeIdVisible, _defaultImpl); case EXTERNAL_PROPERTY: return new AsExternalTypeDeserializer(baseType, idRes, _typeProperty, _typeIdVisible, _defaultImpl); } throw new IllegalStateException("Do not know how to construct standard type serializer for inclusion type: "+_includeAs); }
private void addJsonTypeInfoAnnotation(JDefinedClass jclass, JsonNode node) { if (ruleFactory.getGenerationConfig().getAnnotationStyle() == AnnotationStyle.JACKSON2) { String annotationName = node.get("deserializationClassProperty").asText(); JAnnotationUse jsonTypeInfo = jclass.annotate(JsonTypeInfo.class); jsonTypeInfo.param("use", JsonTypeInfo.Id.CLASS); jsonTypeInfo.param("include", JsonTypeInfo.As.PROPERTY); jsonTypeInfo.param("property", annotationName); } }
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(name = "one", value = PayloadOne.class), @JsonSubTypes.Type(name = "two", value = org.immutables.fixture.jackson.poly2.PayloadTwo.class) }) @JsonProperty("payload") public abstract Payload getPayload();
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME) @JsonSubTypes({ @Type(name = "I", value = Integer.class), @Type(name = "O", value = Double.class) }) // the annotation will be copied to a builder setter public abstract @Nullable Object value();
/** * Initialize object mapper. * * @return the object mapper */ protected ObjectMapper initializeObjectMapper() { final ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); mapper.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC); mapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC); mapper.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); return mapper; }
/** * Configure mapper. * * @param mapper the mapper */ protected void configureObjectMapper(final ObjectMapper mapper) { mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); mapper.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC); mapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC); mapper.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC); if (isDefaultTypingEnabled()) { mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); } mapper.findAndRegisterModules(); }
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonProperty("values") public void setAllowedValues(final Object[] allowedValuesArray) { if (null != allowedValuesArray) { allowedValues = new HashSet<>(Arrays.asList(allowedValuesArray)); } else { allowedValues = new HashSet<>(0); } }
@JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "kdf") @JsonSubTypes({ @JsonSubTypes.Type(value = Aes128CtrKdfParams.class, name = Wallet.AES_128_CTR), @JsonSubTypes.Type(value = ScryptKdfParams.class, name = Wallet.SCRYPT) }) // To support my Ether Wallet keys uncomment this annotation & comment out the above // @JsonDeserialize(using = KdfParamsDeserialiser.class) // Also add the following to the ObjectMapperFactory // objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); public void setKdfparams(KdfParams kdfparams) { this.kdfparams = kdfparams; }
@JsonTypeInfo( use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT, visible = true ) @Override public abstract List<T> getContent();
public JsonAuthenticationSerializer() { this.objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); this.objectMapper.addMixInAnnotations(SimpleGrantedAuthority.class, SimpleGrantedAuthorityMixin.class); this.objectMapper.addMixInAnnotations(Collections.unmodifiableList(Collections.EMPTY_LIST).getClass(), UnmodifiableListMixin.class); this.objectMapper.addMixInAnnotations(Collections.unmodifiableSet(Collections.EMPTY_SET).getClass(), UnmodifiableSetMixin.class); this.objectMapper.addMixInAnnotations(User.class, UserMixin.class); this.objectMapper.addMixInAnnotations(UsernamePasswordAuthenticationToken.class, UsernamePasswordAuthenticationTokenMixin.class); this.objectMapper.addMixInAnnotations(WebAuthenticationDetails.class, WebAuthenticationDetailsMixin.class); }
/** * Private constructor */ private JacksonMapper() { super() ; this.setDefaultTyping(new FilteredTypeResolverBuilder(DefaultTyping.NON_FINAL).init(JsonTypeInfo.Id.MINIMAL_CLASS, null) .inclusion(JsonTypeInfo.As.WRAPPER_OBJECT)) ; this.setSerializationInclusion(JsonInclude.Include.NON_NULL) ; this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) ; this.setConfig(getSerializationConfig().withView(JacksonViews.GeneratorView.class)) ; }
@Autowired public AppConfigService(KvMapperFactory kvMapperFactory, ObjectMapper objectMapper) { // we must use custom configuration of mapper, but need use most options and modules from global mapper this.objectMapper = objectMapper.copy(); StdTypeResolverBuilder trb = new ObjectMapper.DefaultTypeResolverBuilder(ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT); trb.init(JsonTypeInfo.Id.CLASS, new CustomTypeIdResolver()).inclusion(JsonTypeInfo.As.PROPERTY); this.objectMapper.setDefaultTyping(trb); this.objectMapper.registerModule(new KvSupportModule(kvMapperFactory)); }
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) public void setResults(List<HealthCheckResultData> results) { this.results.clear(); if(results != null) { this.results.addAll(results); } }
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) public void setAuthorities(Collection<? extends GrantedAuthority> authorities) { this.authorities.clear(); if(authorities != null) { this.authorities.addAll(authorities.stream().map(GrantedAuthorityImpl::convert).collect(Collectors.toList())); } }
private String getJsonType(Class<?> clazz, JsonTypeInfo typeInfo) { String value; JsonTypeInfo.Id use = typeInfo.use(); switch (use) { case CLASS: value = clazz.getName(); break; case NAME: { JsonSubTypes.Type needed = null; JsonSubTypes subTypes = AnnotationUtils.findAnnotation(clazz, JsonSubTypes.class); if(subTypes != null) { for(JsonSubTypes.Type type: subTypes.value()) { if(type.value().equals(clazz)) { needed = type; break; } } } if(needed == null) { throw new IllegalArgumentException("On " + clazz + " can not find 'JsonSubTypes' record for current type."); } value = needed.name(); break; } default: throw new IllegalArgumentException("On " + clazz + " find unexpected 'JsonTypeInfo.use' value: " + use); } return value; }
private String getPropertyName(JsonTypeInfo typeInfo) { String property = typeInfo.property(); if (property.isEmpty()) { JsonTypeInfo.Id use = typeInfo.use(); property = use.getDefaultPropertyName(); } return property; }
public JsonJacksonCodec() { init(mapObjectMapper); // type info inclusion TypeResolverBuilder<?> mapTyper = new DefaultTypeResolverBuilder(DefaultTyping.NON_FINAL) { public boolean useForType(JavaType t) { switch (_appliesFor) { case NON_CONCRETE_AND_ARRAYS: while (t.isArrayType()) { t = t.getContentType(); } // fall through case OBJECT_AND_NON_CONCRETE: return (t.getRawClass() == Object.class) || !t.isConcrete(); case NON_FINAL: while (t.isArrayType()) { t = t.getContentType(); } // to fix problem with wrong long to int conversion if (t.getRawClass() == Long.class) { return true; } return !t.isFinal(); // includes Object.class default: //case JAVA_LANG_OBJECT: return (t.getRawClass() == Object.class); } } }; mapTyper.init(JsonTypeInfo.Id.CLASS, null); mapTyper.inclusion(JsonTypeInfo.As.PROPERTY); mapObjectMapper.setDefaultTyping(mapTyper); }
@Override protected TypeIdResolver idResolver(MapperConfig<?> config, JavaType baseType, Collection<NamedType> subtypes, boolean forSer, boolean forDeser) { if (_customIdResolver != null) { return _customIdResolver; } if (_idType == null) { throw new IllegalStateException("Can not build, 'init()' not yet called"); } if (_idType == JsonTypeInfo.Id.CLASS){ return new WideningClassNameIdResolver(baseType, config.getTypeFactory()); } return super.idResolver(config, baseType, subtypes, forSer, forDeser); //To change body of generated methods, choose Tools | Templates. }
public NsTypeResolverBuilder(BasicMetaData basicMetaData) { super(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE); this.basicMetaData = basicMetaData; init(JsonTypeInfo.Id.NAME, null); inclusion(JsonTypeInfo.As.PROPERTY); typeProperty(TYPE_PROPERTY_NAME); }
private static ObjectMapper initialize( ObjectMapper mapper, boolean defaultTyping, boolean nonNullInclusion ) { if( mapper instanceof XmlMapper ) { ( ( XmlMapper ) mapper ).setDefaultUseWrapper( false ); } AnnotationIntrospector introspector = new JacksonAnnotationIntrospector(); mapper.getDeserializationConfig().with( introspector ); mapper.getSerializationConfig().with( introspector ); mapper.registerModule( new AfterburnerModule() ); mapper.registerModule( new Jdk8Module().configureAbsentsAsNulls( true ) ); mapper.registerModule( new JodaModule() ); mapper.registerModule( new ParameterNamesModule( JsonCreator.Mode.DEFAULT ) ); mapper.enable( DeserializationFeature.USE_LONG_FOR_INTS ); mapper.enable( JsonParser.Feature.ALLOW_SINGLE_QUOTES ); mapper.disable( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES ); mapper.disable( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS ); mapper.disable( SerializationFeature.WRITE_EMPTY_JSON_ARRAYS ); mapper.disable( SerializationFeature.FAIL_ON_EMPTY_BEANS ); mapper.configure( JsonGenerator.Feature.AUTO_CLOSE_TARGET, false ); mapper.setVisibility( PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY ); if( !nonNullInclusion ) mapper.setSerializationInclusion( JsonInclude.Include.NON_NULL ); modules.forEach( mapper::registerModule ); if( defaultTyping ) mapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY ); return mapper; }
protected TypeResolverBuilder<?> _findTypeResolver(MapperConfig<?> paramMapperConfig, Annotated paramAnnotated, JavaType paramJavaType) { JsonTypeInfo localJsonTypeInfo = (JsonTypeInfo)paramAnnotated.getAnnotation(JsonTypeInfo.class); JsonTypeResolver localJsonTypeResolver = (JsonTypeResolver)paramAnnotated.getAnnotation(JsonTypeResolver.class); Object localObject; if (localJsonTypeResolver != null) { if (localJsonTypeInfo == null) return null; localObject = paramMapperConfig.typeResolverBuilderInstance(paramAnnotated, localJsonTypeResolver.value()); } else { if (localJsonTypeInfo == null) return null; if (localJsonTypeInfo.use() == JsonTypeInfo.Id.NONE) return _constructNoTypeResolverBuilder(); localObject = _constructStdTypeResolverBuilder(); } JsonTypeIdResolver localJsonTypeIdResolver = (JsonTypeIdResolver)paramAnnotated.getAnnotation(JsonTypeIdResolver.class); TypeIdResolver localTypeIdResolver1; if (localJsonTypeIdResolver == null) localTypeIdResolver1 = null; else localTypeIdResolver1 = paramMapperConfig.typeIdResolverInstance(paramAnnotated, localJsonTypeIdResolver.value()); TypeIdResolver localTypeIdResolver2 = localTypeIdResolver1; if (localTypeIdResolver1 != null) localTypeIdResolver2.init(paramJavaType); TypeResolverBuilder localTypeResolverBuilder1 = ((TypeResolverBuilder)localObject).init(localJsonTypeInfo.use(), localTypeIdResolver2); JsonTypeInfo.As localAs1 = localJsonTypeInfo.include(); JsonTypeInfo.As localAs2 = localAs1; if ((localAs1 == JsonTypeInfo.As.EXTERNAL_PROPERTY) && ((paramAnnotated instanceof AnnotatedClass))) localAs2 = JsonTypeInfo.As.PROPERTY; TypeResolverBuilder localTypeResolverBuilder2 = localTypeResolverBuilder1.inclusion(localAs2).typeProperty(localJsonTypeInfo.property()); Class localClass = localJsonTypeInfo.defaultImpl(); if (localClass != JsonTypeInfo.None.class) localTypeResolverBuilder2 = localTypeResolverBuilder2.defaultImpl(localClass); return localTypeResolverBuilder2.typeIdVisibility(localJsonTypeInfo.visible()); }
private String getTypeName(JsonTypeInfo parentJsonTypeInfo, final Class<?> cls) { // Id.CLASS if (parentJsonTypeInfo.use() == JsonTypeInfo.Id.CLASS) { return cls.getName(); } // find @JsonTypeName recursively final JsonTypeName jsonTypeName = getAnnotationRecursive(cls, JsonTypeName.class); if (jsonTypeName != null && !jsonTypeName.value().isEmpty()) { return jsonTypeName.value(); } // find @JsonSubTypes.Type recursively final JsonSubTypes jsonSubTypes = getAnnotationRecursive(cls, JsonSubTypes.class, new Predicate<JsonSubTypes>() { @Override public boolean test(JsonSubTypes types) { return getJsonSubTypeForClass(types, cls) != null; } }); if (jsonSubTypes != null) { final JsonSubTypes.Type jsonSubType = getJsonSubTypeForClass(jsonSubTypes, cls); if (!jsonSubType.name().isEmpty()) { return jsonSubType.name(); } } // use simplified class name if it's not an interface or abstract if(!cls.isInterface() && !Modifier.isAbstract(cls.getModifiers())) { return cls.getName().substring(cls.getName().lastIndexOf(".") + 1); } return null; }