com.fasterxml.jackson.annotation.JsonSubTypes Java Examples

The following examples show how to use com.fasterxml.jackson.annotation.JsonSubTypes. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OpenAPIGenerator.java    From spring-openapi with MIT License 6 votes vote down vote up
private Optional<InheritanceInfo> getInheritanceInfo(Class<?> clazz) {
    if (clazz.getAnnotation(JsonSubTypes.class) != null) {
        List<Annotation> annotations = unmodifiableList(asList(clazz.getAnnotations()));
        JsonTypeInfo jsonTypeInfo = annotations.stream()
                .filter(annotation -> annotation instanceof JsonTypeInfo)
                .map(annotation -> (JsonTypeInfo) annotation)
                .findFirst()
                .orElse(null);

        InheritanceInfo inheritanceInfo = new InheritanceInfo();
        inheritanceInfo.setDiscriminatorFieldName(getDiscriminatorName(jsonTypeInfo));
        inheritanceInfo.setDiscriminatorClassMap(scanJacksonInheritance(annotations));
        return Optional.of(inheritanceInfo);
    }
    return Optional.empty();
}
 
Example #2
Source File: OpenAPIV2Generator.java    From spring-openapi with MIT License 6 votes vote down vote up
private Optional<InheritanceInfo> getInheritanceInfo(Class<?> clazz) {
	if (clazz.getAnnotation(JsonSubTypes.class) != null) {
		List<Annotation> annotations = unmodifiableList(asList(clazz.getAnnotations()));
		JsonTypeInfo jsonTypeInfo = annotations.stream()
											   .filter(annotation -> annotation instanceof JsonTypeInfo)
											   .map(annotation -> (JsonTypeInfo) annotation)
											   .findFirst()
											   .orElse(null);

		InheritanceInfo inheritanceInfo = new InheritanceInfo();
		inheritanceInfo.setDiscriminatorFieldName(getDiscriminatorName(jsonTypeInfo));
		inheritanceInfo.setDiscriminatorClassMap(scanJacksonInheritance(annotations));
		return Optional.of(inheritanceInfo);
	}
	return Optional.empty();
}
 
Example #3
Source File: NodeMapping.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #4
Source File: SlackInteractiveCallbackTest.java    From slack-client with Apache License 2.0 6 votes vote down vote up
@Test
public void checkAllInteractiveCallBackTypesAreMapped() {
  JsonSubTypes jsonSubTypes = SlackInteractiveCallback.class.getAnnotation(JsonSubTypes.class);

  Set<String> types = Arrays
      .stream(jsonSubTypes.value())
      .map(JsonSubTypes.Type::name)
      .collect(Collectors.toSet());


  for (String type : types) {
    assertThat(InteractiveCallbackType.get(type))
        .describedAs("Could not find enum mapping for %s", type)
        .isNotEqualTo(InteractiveCallbackType.UNKNOWN);
  }
}
 
Example #5
Source File: JsonSubTypesResolver.java    From jsonschema-generator with Apache License 2.0 6 votes vote down vote up
@Override
public CustomDefinition provideCustomSchemaDefinition(ResolvedType javaType, SchemaGenerationContext context) {
    Class<?> targetSuperType = javaType.getErasedType();
    JsonTypeInfo typeInfoAnnotation;
    do {
        typeInfoAnnotation = targetSuperType.getAnnotation(JsonTypeInfo.class);
        targetSuperType = targetSuperType.getSuperclass();
    } while (typeInfoAnnotation == null && targetSuperType != null);

    if (typeInfoAnnotation == null || javaType.getErasedType().getDeclaredAnnotation(JsonSubTypes.class) != null) {
        return null;
    }
    ObjectNode definition = this.createSubtypeDefinition(javaType, typeInfoAnnotation, null, context);
    if (definition == null) {
        return null;
    }
    return new CustomDefinition(definition, CustomDefinition.DefinitionType.STANDARD, CustomDefinition.AttributeInclusion.NO);
}
 
Example #6
Source File: JsonSubTypesResolver.java    From jsonschema-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Providing custom schema definition for field/method in case of a per-property override of the applicable subtypes or how they are serialized.
 *
 * @param scope targeted field or method
 * @param context generation context
 * @return applicable custom per-property override schema definition (may be {@code null})
 */
public CustomPropertyDefinition provideCustomPropertySchemaDefinition(MemberScope<?, ?> scope, SchemaGenerationContext context) {
    JsonTypeInfo typeInfoAnnotation = scope.getAnnotationConsideringFieldAndGetter(JsonTypeInfo.class);
    if (typeInfoAnnotation == null || scope.getType().getErasedType().getDeclaredAnnotation(JsonSubTypes.class) != null) {
        return null;
    }
    ObjectNode attributes;
    if (scope instanceof FieldScope) {
        attributes = AttributeCollector.collectFieldAttributes((FieldScope) scope, context);
    } else if (scope instanceof MethodScope) {
        attributes = AttributeCollector.collectMethodAttributes((MethodScope) scope, context);
    } else {
        attributes = null;
    }
    ObjectNode definition = this.createSubtypeDefinition(scope.getType(), typeInfoAnnotation, attributes, context);
    if (definition == null) {
        return null;
    }
    return new CustomPropertyDefinition(definition, CustomDefinition.AttributeInclusion.NO);
}
 
Example #7
Source File: BeanProcessor.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #8
Source File: SchemaGenerator.java    From Poseidon with Apache License 2.0 6 votes vote down vote up
private static void handleJsonSubTypes(Class<?> clazz, ComposedSchema schema, Map<String, Class<?>> referencedClasses) {
        final JsonTypeInfo typeInfo = clazz.getAnnotation(JsonTypeInfo.class);
        final JsonSubTypes subTypes = clazz.getAnnotation(JsonSubTypes.class);

        if (typeInfo != null && subTypes != null) {
            final Discriminator discriminator = new Discriminator().propertyName(typeInfo.property().equals("") ? typeInfo.use().getDefaultPropertyName() : typeInfo.property());

            for (JsonSubTypes.Type type : subTypes.value()) {
                final Schema<?> reference = createReference(type.value(), clazz, referencedClasses);
                schema.addOneOfItem(reference);
                if (StringUtils.isNotEmpty(type.name()) || typeInfo.use() == JsonTypeInfo.Id.CLASS) {
                    // TODO: 2019-06-24 fix this once mappings are correctly handled elsewhere
//                    discriminator.mapping(type.name(), reference.get$ref());
                    discriminator.mapping(typeInfo.use() == JsonTypeInfo.Id.CLASS ? type.value().getName() : type.name(), "#/components/schemas/" + type.value().getSimpleName());
                }
            }

            schema.discriminator(discriminator);
        }
    }
 
Example #9
Source File: ContestModuleDump.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Nullable
@Value.Default
@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
        property = "name",
        visible = true,
        defaultImpl = NoClass.class
)
@JsonSubTypes({
        @JsonSubTypes.Type(value = ImmutableScoreboardModuleConfig.class),
        @JsonSubTypes.Type(value = ImmutableClarificationTimeLimitModuleConfig.class),
        @JsonSubTypes.Type(value = ImmutableFrozenScoreboardModuleConfig.class),
        @JsonSubTypes.Type(value = ImmutableVirtualModuleConfig.class)
})
public ModuleConfig getConfig() {
    return null;
}
 
Example #10
Source File: WalletFile.java    From web3j with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #11
Source File: FilterDto.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
    property = "resourceType", defaultImpl=TaskQueryDto.class)
  @JsonSubTypes(value = {
  @JsonSubTypes.Type(value = TaskQueryDto.class, name = EntityTypes.TASK)})
public void setQuery(AbstractQueryDto<?> query) {
  this.query = query;
}
 
Example #12
Source File: Property.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
static Map<Class<?>, String> subtypeMap(Class<?> crdClass) {
    JsonSubTypes subtypes = crdClass.getAnnotation(JsonSubTypes.class);
    if (subtypes != null) {
        LinkedHashMap<Class<?>, String> result = new LinkedHashMap<>(subtypes.value().length);
        for (JsonSubTypes.Type type : subtypes.value()) {
            result.put(type.value(), type.name());
        }
        return result;
    } else {
        return emptyMap();
    }
}
 
Example #13
Source File: Property.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
static List<String> subtypeNames(Class<?> crdClass) {
    JsonSubTypes subtypes = crdClass.getAnnotation(JsonSubTypes.class);
    if (subtypes != null) {
        ArrayList<String> result = new ArrayList<>(subtypes.value().length);
        for (JsonSubTypes.Type type : subtypes.value()) {
            result.add(type.name());
        }
        return result;
    } else {
        return emptyList();
    }
}
 
Example #14
Source File: NodeMapping.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #15
Source File: JobConfiguration.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * The sub type names refer to the {@link JobType} enumeration. Defaults to null for unmapped job types.
 */
@JacksonXmlProperty
@JsonProperty
@Property( required = FALSE )
@JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "jobType", defaultImpl = java.lang.Void.class )
@JsonSubTypes( value = {
    @JsonSubTypes.Type( value = AnalyticsJobParameters.class, name = "ANALYTICS_TABLE" ),
    @JsonSubTypes.Type( value = ContinuousAnalyticsJobParameters.class, name = "CONTINUOUS_ANALYTICS_TABLE" ),
    @JsonSubTypes.Type( value = MonitoringJobParameters.class, name = "MONITORING" ),
    @JsonSubTypes.Type( value = PredictorJobParameters.class, name = "PREDICTOR" ),
    @JsonSubTypes.Type( value = PushAnalysisJobParameters.class, name = "PUSH_ANALYSIS" ),
    @JsonSubTypes.Type( value = SmsJobParameters.class, name = "SMS_SEND" ),
    @JsonSubTypes.Type( value = MetadataSyncJobParameters.class, name = "META_DATA_SYNC" ),
    @JsonSubTypes.Type( value = EventProgramsDataSynchronizationJobParameters.class, name = "EVENT_PROGRAMS_DATA_SYNC" ),
    @JsonSubTypes.Type( value = TrackerProgramsDataSynchronizationJobParameters.class, name = "TRACKER_PROGRAMS_DATA_SYNC" ),
    @JsonSubTypes.Type( value = DataSynchronizationJobParameters.class, name = "DATA_SYNC" )
} )
public JobParameters getJobParameters()
{
    return jobParameters;
}
 
Example #16
Source File: Jackson2Parser.java    From typescript-generator with MIT License 5 votes vote down vote up
private static JsonSubTypes.Type getJsonSubTypeForClass(JsonSubTypes types, Class<?> cls) {
    for (JsonSubTypes.Type type : types.value()) {
        if (type.value().equals(cls)) {
            return type;
        }
    }
    return null;
}
 
Example #17
Source File: TypeGuardsForJackson2PolymorphismExtension.java    From typescript-generator with MIT License 5 votes vote down vote up
@Override
public void emitElements(Writer writer, Settings settings, boolean exportKeyword, TsModel model) {
    for (TsBeanModel tsBean : model.getBeans()) {
        final Class<?> beanClass = tsBean.getOrigin();
        if (beanClass != null) {
            final JsonSubTypes jsonSubTypes = beanClass.getAnnotation(JsonSubTypes.class);
            final JsonTypeInfo jsonTypeInfo = beanClass.getAnnotation(JsonTypeInfo.class);
            if (jsonSubTypes != null && jsonTypeInfo != null && jsonTypeInfo.include() == JsonTypeInfo.As.PROPERTY) {
                final String propertyName = jsonTypeInfo.property();
                for (JsonSubTypes.Type subType : jsonSubTypes.value()) {
                    String propertyValue = null;
                    if (jsonTypeInfo.use() == JsonTypeInfo.Id.NAME) {
                        if (subType.name().equals("")) {
                            final JsonTypeName jsonTypeName = subType.value().getAnnotation(JsonTypeName.class);
                            if (jsonTypeName != null) {
                                propertyValue = jsonTypeName.value();
                            }
                        } else {
                            propertyValue = subType.name();
                        }
                    }
                    if (propertyValue != null) {
                        final String baseTypeName = tsBean.getName().getSimpleName();
                        final String subTypeName = findTypeName(subType.value(), model);
                        if (baseTypeName != null && subTypeName != null) {
                            writer.writeIndentedLine("");
                            emitTypeGuard(writer, settings, exportKeyword, baseTypeName, subTypeName, propertyName, propertyValue);
                        }
                    }
                }
            }
        }
    }
}
 
Example #18
Source File: Channel.java    From chromecast-java-api-v2 with Apache License 2.0 5 votes vote down vote up
private boolean isAppEvent(JsonNode parsed) {
    if (parsed != null && parsed.has("responseType")) {
        String type = parsed.get("responseType").asText();
        for (JsonSubTypes.Type t : STANDARD_RESPONSE_TYPES) {
            if (t.name().equals(type)) {
                return false;
            }
        }
    }
    return parsed == null || !parsed.has("requestId");
}
 
Example #19
Source File: PropertyProcessor.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
private static void processBeanAnnotation( TreeLogger logger, JacksonTypeOracle typeOracle, RebindConfiguration configuration, JType
        type, PropertyAccessors propertyAccessors, PropertyInfoBuilder builder ) throws UnableToCompleteException {

    // identity
    Optional<JsonIdentityInfo> jsonIdentityInfo = propertyAccessors.getAnnotation( JsonIdentityInfo.class );
    Optional<JsonIdentityReference> jsonIdentityReference = propertyAccessors.getAnnotation( JsonIdentityReference.class );

    // type info
    Optional<JsonTypeInfo> jsonTypeInfo = propertyAccessors.getAnnotation( JsonTypeInfo.class );
    Optional<JsonSubTypes> propertySubTypes = propertyAccessors.getAnnotation( JsonSubTypes.class );

    // if no annotation is present that overrides bean processing, we just stop now
    if ( !jsonIdentityInfo.isPresent() && !jsonIdentityReference.isPresent() && !jsonTypeInfo.isPresent() && !propertySubTypes
            .isPresent() ) {
        // no override on field
        return;
    }

    // we need to find the bean to apply annotation on
    Optional<JClassType> beanType = extractBeanType( logger, typeOracle, type, builder.getPropertyName() );

    if ( beanType.isPresent() ) {
        if ( jsonIdentityInfo.isPresent() || jsonIdentityReference.isPresent() ) {
            builder.setIdentityInfo( BeanProcessor.processIdentity( logger, typeOracle, configuration, beanType
                    .get(), jsonIdentityInfo, jsonIdentityReference ) );
        }

        if ( jsonTypeInfo.isPresent() || propertySubTypes.isPresent() ) {
            builder.setTypeInfo( BeanProcessor.processType( logger, typeOracle, configuration, beanType
                    .get(), jsonTypeInfo, propertySubTypes ) );
        }
    } else {
        logger.log( Type.WARN, "Annotation present on property " + builder.getPropertyName() + " but no valid bean has been found." );
    }
}
 
Example #20
Source File: BeanProcessor.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
/**
 * <p>processType</p>
 *
 * @param logger a {@link com.google.gwt.core.ext.TreeLogger} object.
 * @param typeOracle a {@link com.github.nmorel.gwtjackson.rebind.JacksonTypeOracle} object.
 * @param configuration a {@link com.github.nmorel.gwtjackson.rebind.RebindConfiguration} object.
 * @param typeOracle a {@link com.github.nmorel.gwtjackson.rebind.JacksonTypeOracle} object.
 * @param type a {@link com.google.gwt.core.ext.typeinfo.JClassType} object.
 * @param jsonTypeInfo a {@link com.google.gwt.thirdparty.guava.common.base.Optional} object.
 * @param propertySubTypes a {@link com.google.gwt.thirdparty.guava.common.base.Optional} object.
 * @return a {@link com.google.gwt.thirdparty.guava.common.base.Optional} object.
 * @throws com.google.gwt.core.ext.UnableToCompleteException if any.
 */
public static Optional<BeanTypeInfo> processType( TreeLogger logger, JacksonTypeOracle typeOracle, RebindConfiguration configuration,
                                                  JClassType type, Optional<JsonTypeInfo> jsonTypeInfo, Optional<JsonSubTypes>
        propertySubTypes ) throws UnableToCompleteException {

    if ( !jsonTypeInfo.isPresent() ) {
        jsonTypeInfo = findFirstEncounteredAnnotationsOnAllHierarchy( configuration, type, JsonTypeInfo.class );
        if ( !jsonTypeInfo.isPresent() ) {
            return Optional.absent();
        }
    }

    Id use = jsonTypeInfo.get().use();
    As include = jsonTypeInfo.get().include();
    String propertyName = jsonTypeInfo.get().property().isEmpty() ? jsonTypeInfo.get().use().getDefaultPropertyName() : jsonTypeInfo
            .get().property();

    Optional<JsonSubTypes> typeSubTypes = findFirstEncounteredAnnotationsOnAllHierarchy( configuration, type, JsonSubTypes.class );

    // TODO we could do better, we actually extract metadata twice for a lot of classes
    ImmutableMap<JClassType, String> classToSerializationMetadata = extractMetadata( logger, configuration, type, jsonTypeInfo,
            propertySubTypes, typeSubTypes, CreatorUtils
                    .filterSubtypesForSerialization( logger, configuration, type ) );
    ImmutableMap<JClassType, String> classToDeserializationMetadata = extractMetadata( logger, configuration, type, jsonTypeInfo,
            propertySubTypes, typeSubTypes, CreatorUtils
                    .filterSubtypesForDeserialization( logger, configuration, type ) );

    return Optional.of(
            new BeanTypeInfo( use, include, propertyName, classToSerializationMetadata, classToDeserializationMetadata ) );
}
 
Example #21
Source File: BeanProcessor.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
private static String extractTypeMetadata( TreeLogger logger, RebindConfiguration configuration, JClassType baseType, JClassType
        subtype, JsonTypeInfo typeInfo, Optional<JsonSubTypes> propertySubTypes, Optional<JsonSubTypes> baseSubTypes,
                                           ImmutableList<JClassType> allSubtypes ) throws UnableToCompleteException {
    switch ( typeInfo.use() ) {
        case NAME:
            // we first look the name on JsonSubTypes annotations. Top ones override the bottom ones.
            String name = findNameOnJsonSubTypes( baseType, subtype, allSubtypes, propertySubTypes, baseSubTypes );
            if ( null != name && !"".equals( name ) ) {
                return name;
            }

            // we look if the name is defined on the type with JsonTypeName
            Optional<JsonTypeName> typeName = findFirstEncounteredAnnotationsOnAllHierarchy( configuration, subtype, JsonTypeName
                    .class );
            if ( typeName.isPresent() && !Strings.isNullOrEmpty( typeName.get().value() ) ) {
                return typeName.get().value();
            }

            // we use the default name (ie simple name of the class)
            String simpleBinaryName = subtype.getQualifiedBinaryName();
            int indexLastDot = simpleBinaryName.lastIndexOf( '.' );
            if ( indexLastDot != -1 ) {
                simpleBinaryName = simpleBinaryName.substring( indexLastDot + 1 );
            }
            return simpleBinaryName;
        case MINIMAL_CLASS:
            if ( !baseType.getPackage().isDefault() ) {
                String basePackage = baseType.getPackage().getName();
                if ( subtype.getQualifiedBinaryName().startsWith( basePackage + "." ) ) {
                    return subtype.getQualifiedBinaryName().substring( basePackage.length() );
                }
            }
        case CLASS:
            return subtype.getQualifiedBinaryName();
        default:
            logger.log( TreeLogger.Type.ERROR, "JsonTypeInfo.Id." + typeInfo.use() + " is not supported" );
            throw new UnableToCompleteException();
    }
}
 
Example #22
Source File: BeanProcessor.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
private static String findNameOnJsonSubTypes( JClassType baseType, JClassType subtype, ImmutableList<JClassType> allSubtypes,
                                              Optional<JsonSubTypes> propertySubTypes, Optional<JsonSubTypes> baseSubTypes ) {
    JsonSubTypes.Type typeFound = findTypeOnSubTypes( subtype, propertySubTypes );
    if ( null != typeFound ) {
        return typeFound.name();
    }

    typeFound = findTypeOnSubTypes( subtype, baseSubTypes );
    if ( null != typeFound ) {
        return typeFound.name();
    }

    if ( baseType != subtype ) {
        // we look in all the hierarchy
        JClassType type = subtype;
        while ( null != type ) {
            if ( allSubtypes.contains( type ) ) {
                JsonSubTypes.Type found = findTypeOnSubTypes( subtype, Optional.fromNullable( type
                        .getAnnotation( JsonSubTypes.class ) ) );
                if ( null != found ) {
                    typeFound = found;
                }
            }
            type = type.getSuperclass();
        }

        if ( null != typeFound ) {
            return typeFound.name();
        }
    }

    return null;
}
 
Example #23
Source File: BeanProcessor.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
private static JsonSubTypes.Type findTypeOnSubTypes( JClassType subtype, Optional<JsonSubTypes> jsonSubTypes ) {
    if ( jsonSubTypes.isPresent() ) {
        for ( JsonSubTypes.Type type : jsonSubTypes.get().value() ) {
            if ( type.value().getName().equals( subtype.getQualifiedBinaryName() ) ) {
                return type;
            }
        }
    }
    return null;
}
 
Example #24
Source File: _AbstractResponse.java    From immutables with Apache License 2.0 5 votes vote down vote up
@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();
 
Example #25
Source File: CustomBuilderDeserialize.java    From immutables with Apache License 2.0 5 votes vote down vote up
@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();
 
Example #26
Source File: OpenApiClientGenerator.java    From spring-openapi with MIT License 5 votes vote down vote up
private void parseDiscriminator(TypeSpec.Builder typeSpecBuilder, Discriminator discriminator, String targetPackage,
								boolean generateDiscriminatorProperty) {
	if (discriminator.getPropertyName() != null) {
		AnnotationSpec.Builder annotationSpecBuilder = AnnotationSpec.builder(JsonTypeInfo.class)
				.addMember("use", "JsonTypeInfo.Id.NAME")
				.addMember("include", "JsonTypeInfo.As.PROPERTY")
				.addMember("property", "$S", discriminator.getPropertyName());
		if (generateDiscriminatorProperty) {
			annotationSpecBuilder.addMember("visible", "true");
		}
		typeSpecBuilder.addAnnotation(annotationSpecBuilder.build());
	}
	if (discriminator.getMapping() != null) {
		List<AnnotationSpec> annotationSpecs = discriminator.getMapping().entrySet().stream()
				.map(discriminatorMappingEntry ->
						AnnotationSpec.builder(Type.class)
								.addMember("value", "$T.class", ClassName.get(targetPackage, discriminatorMappingEntry.getValue()))
								.addMember("name", "$S", discriminatorMappingEntry.getKey())
								.build())
				.collect(Collectors.toList());

		AnnotationSpec jsonSubTypesAnnotation = AnnotationSpec.builder(JsonSubTypes.class)
				.addMember("value", wrapAnnotationsIntoArray(annotationSpecs))
				.build();

		typeSpecBuilder.addAnnotation(jsonSubTypesAnnotation);
	}
}
 
Example #27
Source File: ContestStyleDump.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
        property = "name",
        visible = true
)
@JsonSubTypes({
        @JsonSubTypes.Type(value = ImmutableIoiStyleModuleConfig.class),
        @JsonSubTypes.Type(value = ImmutableIcpcStyleModuleConfig.class),
        @JsonSubTypes.Type(value = ImmutableGcjStyleModuleConfig.class),
        @JsonSubTypes.Type(value = ImmutableBundleStyleModuleConfig.class)
})
StyleModuleConfig getConfig();
 
Example #28
Source File: OpenAPIGenerator.java    From spring-openapi with MIT License 5 votes vote down vote up
private Map<String, String> scanJacksonInheritance(List<Annotation> annotations) {
    return annotations.stream()
            .filter(annotation -> annotation instanceof JsonSubTypes)
            .map(annotation -> (JsonSubTypes) annotation)
            .flatMap(jsonSubTypesMapped -> Arrays.stream(jsonSubTypesMapped.value()))
            .collect(Collectors.toMap(o -> o.value().getSimpleName(), JsonSubTypes.Type::name));
}
 
Example #29
Source File: OpenAPIV2Generator.java    From spring-openapi with MIT License 5 votes vote down vote up
private Map<String, String> scanJacksonInheritance(List<Annotation> annotations) {
	return annotations.stream()
					  .filter(annotation -> annotation instanceof JsonSubTypes)
					  .map(annotation -> (JsonSubTypes) annotation)
					  .flatMap(jsonSubTypesMapped -> Arrays.stream(jsonSubTypesMapped.value()))
					  .collect(Collectors.toMap(o -> o.value().getCanonicalName(), JsonSubTypes.Type::name));
}
 
Example #30
Source File: JsonSubTypesResolver.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Look-up applicable subtypes for the given field/method if there is a {@link JsonSubTypes} annotation.
 *
 * @param property targeted field/method
 * @return list of annotated subtypes (or {@code null} if there is no {@link JsonSubTypes} annotation)
 */
public List<ResolvedType> findTargetTypeOverrides(MemberScope<?, ?> property) {
    if (property.getType() == null) {
        return null;
    }
    JsonSubTypes subtypesAnnotation = property.getAnnotationConsideringFieldAndGetter(JsonSubTypes.class);
    return this.lookUpSubtypesFromAnnotation(property.getType(), subtypesAnnotation, property.getContext());
}