Java Examples for com.fasterxml.jackson.annotation.JsonSubTypes

The following java examples will help you to understand the usage of com.fasterxml.jackson.annotation.JsonSubTypes. These source code samples are taken from different open source projects.

Example 1
Project: javersion-master  File: JacksonMappingResolver.java View source code
@Nonnull
@Override
public Result<Map<TypeDescriptor, String>> subclasses(TypeDescriptor type) {
    JsonSubTypes jsonSubType = type.getAnnotation(JsonSubTypes.class);
    if (jsonSubType != null && jsonSubType.value().length > 0) {
        TypeDescriptors typeDescriptors = type.getTypeDescriptors();
        Map<TypeDescriptor, String> aliasesByTypes = asList(jsonSubType.value()).stream().collect(toMap( subType -> typeDescriptors.get(subType.value()), Type::name));
        return Result.of(aliasesByTypes);
    }
    return Result.notFound();
}
Example 2
Project: gwt-rest-master  File: JsonEncoderDecoderClassCreator.java View source code
private List<Subtype> getPossibleTypes(final JsonTypeInfo typeInfo, final boolean isLeaf) throws UnableToCompleteException {
    if (typeInfo == null)
        return Lists.newArrayList(new Subtype(null, source));
    Collection<Type> subTypes = findJsonSubTypes(source);
    if (subTypes.isEmpty()) {
        JsonSubTypes foundAnnotation = getAnnotation(source, JsonSubTypes.class);
        if (foundAnnotation != null) {
            Type[] value = foundAnnotation.value();
            subTypes = Arrays.asList(value);
        }
    }
    PossibleTypesVisitor v = new PossibleTypesVisitor(context, source, isLeaf, getLogger(), subTypes);
    return v.visit(typeInfo.use());
}
Example 3
Project: resty-gwt-master  File: JsonEncoderDecoderClassCreator.java View source code
private List<Subtype> getPossibleTypes(final JsonTypeInfo typeInfo, final boolean isLeaf) throws UnableToCompleteException {
    if (typeInfo == null)
        return Lists.newArrayList(new Subtype(null, source));
    Collection<Type> subTypes = findJsonSubTypes(source);
    if (subTypes.isEmpty()) {
        JsonSubTypes foundAnnotation = getAnnotation(source, JsonSubTypes.class);
        if (foundAnnotation != null) {
            Type[] value = foundAnnotation.value();
            subTypes = Arrays.asList(value);
        }
    }
    PossibleTypesVisitor v = new PossibleTypesVisitor(context, source, isLeaf, getLogger(), subTypes);
    return v.visit(typeInfo.use());
}
Example 4
Project: verjson-master  File: ObjectMapperFactory.java View source code
protected static Class<?> generateMixIn(Class<?> parent, Set<Pair<Class<?>, String>> childs) {
    ClassPool pool = ClassPool.getDefault();
    String className = parent.getPackage().getName() + ".Gen" + parent.getSimpleName() + "MixIn";
    CtClass ctClass = pool.getOrNull(className);
    Class<?> result = null;
    if (ctClass == null) {
        // TODO check inner classes in parentname
        ctClass = pool.makeClass(className);
        ClassFile cf = ctClass.getClassFile();
        cf.setMajorVersion(ClassFile.JAVA_7);
        cf.setMinorVersion(0);
        ConstPool cp = cf.getConstPool();
        // @JsonTypeInfo
        Annotation annotationInfo = new Annotation(JsonTypeInfo.class.getName(), cp);
        EnumMemberValue enumId = new EnumMemberValue(cp);
        enumId.setType(JsonTypeInfo.Id.class.getName());
        enumId.setValue(JsonTypeInfo.Id.NAME.toString());
        annotationInfo.addMemberValue("use", enumId);
        EnumMemberValue enumAs = new EnumMemberValue(cp);
        enumAs.setType(JsonTypeInfo.As.class.getName());
        enumAs.setValue(As.PROPERTY.toString());
        annotationInfo.addMemberValue("include", enumAs);
        annotationInfo.addMemberValue("property", new StringMemberValue("$type", cp));
        AnnotationsAttribute attr = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag);
        attr.addAnnotation(annotationInfo);
        ClassMemberValue cmvNone = new ClassMemberValue(Void.class.getName(), cp);
        annotationInfo.addMemberValue("defaultImpl", cmvNone);
        // @JsonSubTypes
        List<AnnotationMemberValue> amvs = Lists.newArrayList();
        for (Pair<Class<?>, String> child : childs) {
            Annotation annotationType = new Annotation(Type.class.getName(), cp);
            annotationType.addMemberValue("value", new ClassMemberValue(child.getKey().getName(), cp));
            annotationType.addMemberValue("name", new StringMemberValue(child.getValue(), cp));
            AnnotationMemberValue amv = new AnnotationMemberValue(cp);
            amv.setValue(annotationType);
            amvs.add(amv);
        }
        Annotation annotationSub = new Annotation(JsonSubTypes.class.getName(), cp);
        ArrayMemberValue arraymv = new ArrayMemberValue(cp);
        MemberValue[] valueSubs = amvs.toArray(new MemberValue[] {});
        arraymv.setValue(valueSubs);
        annotationSub.addMemberValue("value", arraymv);
        attr.addAnnotation(annotationSub);
        cf.addAttribute(attr);
        try {
            result = ctClass.toClass();
        } catch (CannotCompileException ex) {
            throw new RuntimeException("Failed generating MixIn for registered Subclasses (" + className + ")", ex);
        }
    } else {
        try {
            result = Class.forName(className);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException("Failed loading generated MixIn (" + className + ")", ex);
        }
    }
    return result;
}
Example 5
Project: raml-for-jax-rs-master  File: JacksonDiscriminatorInheritanceTypeExtension.java View source code
@Override
public void onTypeDeclaration(CurrentBuild currentBuild, TypeSpec.Builder typeSpec, V10GType type) {
    ObjectTypeDeclaration otr = (ObjectTypeDeclaration) type.implementation();
    if (otr.discriminator() != null && type.childClasses(type.name()).size() > 0) {
        typeSpec.addAnnotation(AnnotationSpec.builder(JsonTypeInfo.class).addMember("use", "$T.Id.NAME", JsonTypeInfo.class).addMember("include", "$T.As.PROPERTY", JsonTypeInfo.class).addMember("property", "$S", otr.discriminator()).build());
        AnnotationSpec.Builder subTypes = AnnotationSpec.builder(JsonSubTypes.class);
        for (V10GType gType : type.childClasses(type.name())) {
            subTypes.addMember("value", "$L", AnnotationSpec.builder(JsonSubTypes.Type.class).addMember("value", "$L", gType.defaultJavaTypeName(currentBuild.getModelPackage()) + ".class").build());
        }
        typeSpec.addAnnotation(subTypes.build());
    }
    if (otr.discriminatorValue() != null) {
        typeSpec.addAnnotation(AnnotationSpec.builder(JsonTypeName.class).addMember("value", "$S", otr.discriminatorValue()).build());
    }
    if (type.childClasses(type.name()).size() == 0 && !Annotations.ABSTRACT.get(type)) {
        typeSpec.addAnnotation(AnnotationSpec.builder(JsonDeserialize.class).addMember("as", "$L.class", type.javaImplementationName(currentBuild.getModelPackage())).build());
    }
}
Example 6
Project: torodb-master  File: AbstractBackendSerializer.java View source code
@Override
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType type) throws JsonMappingException {
    if (visitor == null) {
        return;
    }
    JsonObjectFormatVisitor v = visitor.expectObjectFormat(type);
    SerializerProvider prov = visitor.getProvider();
    final SerializationConfig config = prov.getConfig();
    BeanDescription beanDesc = config.introspect(type);
    JsonSubTypes jsonSubTypes;
    if (v != null) {
        for (BeanPropertyDefinition propDef : beanDesc.findProperties()) {
            if (propDef.isExplicitlyIncluded()) {
                jsonSubTypes = propDef.getPrimaryMember().getAnnotation(JsonSubTypes.class);
                if (jsonSubTypes != null) {
                    for (JsonSubTypes.Type jsonSubType : jsonSubTypes.value()) {
                        JavaType subType = TypeFactory.defaultInstance().constructType(jsonSubType.value());
                        depositSchemaProperty(v, jsonSubType.name(), subType);
                    }
                } else {
                    depositSchemaProperty(v, propDef.getName(), propDef.getPrimaryMember().getType(beanDesc.bindingsForBeanType()));
                }
            }
        }
    }
}
Example 7
Project: ari4java-master  File: DefMapper.java View source code
/**
     * Loads definitions from a module.
     *
     * @param f The source .json file
     * @param apiVersion The version of the API we are working with
     * @param modelHasEvents whether this file generates WS events
     * @throws IOException
     */
public void parseJsonDefinition(File f, String apiVersion, boolean modelHasEvents) throws IOException {
    ObjectMapper om = new ObjectMapper();
    System.out.println("Loading as: " + f.getAbsolutePath());
    JsonNode rootNode = om.readTree(f);
    List<Model> lModels = loadModels(rootNode.get("models"), f, apiVersion);
    Apis api1 = loadApis(rootNode.get("apis"), f, apiVersion);
    mymodels.addAll(lModels);
    myAPIs.add(api1);
    if (modelHasEvents) {
        Model typeMessage = null;
        List<Model> otherModels = new ArrayList<Model>();
        for (Model m : lModels) {
            if (m.className.equalsIgnoreCase("Message")) {
                typeMessage = m;
            } else {
                otherModels.add(m);
            }
        }
        String defs = "";
        for (Model m : otherModels) {
            if (defs.length() > 0) {
                defs += ", ";
            }
            defs += "@Type(value = " + m.getImplName() + ".class, name = \"" + m.getInterfaceName() + "\")\n";
        }
        typeMessage.additionalPreambleText = "" + " @JsonTypeInfo(  " + "     use = JsonTypeInfo.Id.NAME,  " + "     include = JsonTypeInfo.As.PROPERTY,  " + "     property = \"type\") \n " + " @JsonSubTypes({  " + defs + " })  \n\n";
        typeMessage.imports.add("com.fasterxml.jackson.annotation.JsonSubTypes");
        typeMessage.imports.add("com.fasterxml.jackson.annotation.JsonSubTypes.Type");
        typeMessage.imports.add("com.fasterxml.jackson.annotation.JsonTypeInfo");
    }
    // Now generate the interface
    for (Model m : mymodels) {
        JavaInterface j = interfaces.get(m.getInterfaceName());
        if (j == null) {
            j = new JavaInterface();
            j.pkgName = "ch.loway.oss.ari4java.generated";
            j.className = m.getInterfaceName();
            interfaces.put(m.getInterfaceName(), j);
        }
        m.registerInterfaces(j, apiVersion);
    }
    //for ( Apis api: myAPIs ) {
    JavaInterface j = interfaces.get(api1.getInterfaceName());
    if (j == null) {
        j = new JavaInterface();
        j.pkgName = "ch.loway.oss.ari4java.generated";
        j.className = api1.getInterfaceName();
        interfaces.put(api1.getInterfaceName(), j);
    }
    api1.registerInterfaces(j, apiVersion);
//}
//        //
//        for ( String ifName: interfaces.keySet() ) {
//            JavaInterface ji = interfaces.get(ifName);
////            saveToDisk(ji);
//        }
}
Example 8
Project: typescript-generator-master  File: Jackson2Parser.java View source code
private BeanModel parseBean(SourceType<Class<?>> sourceClass) {
    final List<PropertyModel> properties = new ArrayList<>();
    final BeanHelper beanHelper = getBeanHelper(sourceClass.type);
    if (beanHelper != null) {
        for (BeanPropertyWriter beanPropertyWriter : beanHelper.getProperties()) {
            final Member propertyMember = beanPropertyWriter.getMember().getMember();
            Type propertyType = getGenericType(propertyMember);
            if (propertyType == JsonNode.class) {
                propertyType = Object.class;
            }
            boolean isInAnnotationFilter = settings.includePropertyAnnotations.isEmpty();
            if (!isInAnnotationFilter) {
                for (Class<? extends Annotation> optionalAnnotation : settings.includePropertyAnnotations) {
                    if (beanPropertyWriter.getAnnotation(optionalAnnotation) != null) {
                        isInAnnotationFilter = true;
                        break;
                    }
                }
                if (!isInAnnotationFilter) {
                    System.out.println("Skipping " + sourceClass.type + "." + beanPropertyWriter.getName() + " because it is missing an annotation from includePropertyAnnotations!");
                    continue;
                }
            }
            boolean optional = false;
            for (Class<? extends Annotation> optionalAnnotation : settings.optionalAnnotations) {
                if (beanPropertyWriter.getAnnotation(optionalAnnotation) != null) {
                    optional = true;
                    break;
                }
            }
            // @JsonUnwrapped
            PropertyModel.PullProperties pullProperties = null;
            final Member originalMember = beanPropertyWriter.getMember().getMember();
            if (originalMember instanceof AccessibleObject) {
                final AccessibleObject accessibleObject = (AccessibleObject) originalMember;
                final JsonUnwrapped annotation = accessibleObject.getAnnotation(JsonUnwrapped.class);
                if (annotation != null && annotation.enabled()) {
                    pullProperties = new PropertyModel.PullProperties(annotation.prefix(), annotation.suffix());
                }
            }
            properties.add(processTypeAndCreateProperty(beanPropertyWriter.getName(), propertyType, optional, sourceClass.type, originalMember, pullProperties));
        }
    }
    if (sourceClass.type.isEnum()) {
        return new BeanModel(sourceClass.type, null, null, null, null, null, properties, null);
    }
    final String discriminantProperty;
    final String discriminantLiteral;
    final JsonTypeInfo jsonTypeInfo = sourceClass.type.getAnnotation(JsonTypeInfo.class);
    final JsonTypeInfo parentJsonTypeInfo;
    if (isSupported(jsonTypeInfo)) {
        // this is parent
        discriminantProperty = getDiscriminantPropertyName(jsonTypeInfo);
        discriminantLiteral = null;
    } else if (!sourceClass.type.isInterface() && !Modifier.isAbstract(sourceClass.type.getModifiers()) && isSupported(parentJsonTypeInfo = getAnnotationRecursive(sourceClass.type, JsonTypeInfo.class))) {
        // this is child class
        discriminantProperty = getDiscriminantPropertyName(parentJsonTypeInfo);
        discriminantLiteral = getTypeName(sourceClass.type);
    } else {
        // not part of explicit hierarchy
        discriminantProperty = null;
        discriminantLiteral = null;
    }
    final List<Class<?>> taggedUnionClasses;
    final JsonSubTypes jsonSubTypes = sourceClass.type.getAnnotation(JsonSubTypes.class);
    if (jsonSubTypes != null) {
        taggedUnionClasses = new ArrayList<>();
        for (JsonSubTypes.Type type : jsonSubTypes.value()) {
            addBeanToQueue(new SourceType<>(type.value(), sourceClass.type, "<subClass>"));
            taggedUnionClasses.add(type.value());
        }
    } else {
        taggedUnionClasses = null;
    }
    final Type superclass = sourceClass.type.getGenericSuperclass() == Object.class ? null : sourceClass.type.getGenericSuperclass();
    if (superclass != null) {
        addBeanToQueue(new SourceType<>(superclass, sourceClass.type, "<superClass>"));
    }
    final List<Type> interfaces = Arrays.asList(sourceClass.type.getGenericInterfaces());
    for (Type aInterface : interfaces) {
        addBeanToQueue(new SourceType<>(aInterface, sourceClass.type, "<interface>"));
    }
    return new BeanModel(sourceClass.type, superclass, taggedUnionClasses, discriminantProperty, discriminantLiteral, interfaces, properties, null);
}
Example 9
Project: enunciate-master  File: EnunciateJacksonContext.java View source code
/**
   * Add any type definitions that are specified as "see also".
   *
   * @param declaration The declaration.
   */
protected void addSeeAlsoTypeDefinitions(Element declaration, LinkedList<Element> stack) {
    JsonSubTypes subTypes = declaration.getAnnotation(JsonSubTypes.class);
    if (subTypes != null) {
        Elements elementUtils = getContext().getProcessingEnvironment().getElementUtils();
        Types typeUtils = getContext().getProcessingEnvironment().getTypeUtils();
        JsonSubTypes.Type[] types = subTypes.value();
        for (JsonSubTypes.Type type : types) {
            try {
                stack.push(elementUtils.getTypeElement(JsonSubTypes.class.getName()));
                Class clazz = type.value();
                add(createTypeDefinition(elementUtils.getTypeElement(clazz.getName())), stack);
            } catch (MirroredTypeException e) {
                TypeMirror mirror = e.getTypeMirror();
                Element element = typeUtils.asElement(mirror);
                if (element instanceof TypeElement) {
                    add(createTypeDefinition((TypeElement) element), stack);
                }
            } catch (MirroredTypesException e) {
                List<? extends TypeMirror> mirrors = e.getTypeMirrors();
                for (TypeMirror mirror : mirrors) {
                    Element element = typeUtils.asElement(mirror);
                    if (element instanceof TypeElement) {
                        add(createTypeDefinition((TypeElement) element), stack);
                    }
                }
            } finally {
                stack.pop();
            }
        }
    }
    JsonSeeAlso seeAlso = declaration.getAnnotation(JsonSeeAlso.class);
    if (seeAlso != null) {
        Elements elementUtils = getContext().getProcessingEnvironment().getElementUtils();
        Types typeUtils = getContext().getProcessingEnvironment().getTypeUtils();
        stack.push(elementUtils.getTypeElement(JsonSeeAlso.class.getName()));
        try {
            Class[] classes = seeAlso.value();
            for (Class clazz : classes) {
                add(createTypeDefinition(elementUtils.getTypeElement(clazz.getName())), stack);
            }
        } catch (MirroredTypeException e) {
            TypeMirror mirror = e.getTypeMirror();
            Element element = typeUtils.asElement(mirror);
            if (element instanceof TypeElement) {
                add(createTypeDefinition((TypeElement) element), stack);
            }
        } catch (MirroredTypesException e) {
            List<? extends TypeMirror> mirrors = e.getTypeMirrors();
            for (TypeMirror mirror : mirrors) {
                Element element = typeUtils.asElement(mirror);
                if (element instanceof TypeElement) {
                    add(createTypeDefinition((TypeElement) element), stack);
                }
            }
        } finally {
            stack.pop();
        }
    }
    if (subTypes == null && seeAlso == null && declaration instanceof TypeElement) {
        // No annotation tells us what to do, so we'll look up subtypes and add them
        for (Element el : getContext().getApiElements()) {
            if ((el instanceof TypeElement) && !((TypeElement) el).getQualifiedName().contentEquals(((TypeElement) declaration).getQualifiedName()) && ((DecoratedTypeMirror) el.asType()).isInstanceOf(declaration)) {
                add(createTypeDefinition((TypeElement) el), stack);
            }
        }
    }
}
Example 10
Project: gwt-jackson-master  File: PropertyProcessor.java View source code
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 11
Project: api-themoviedb-master  File: PersonCreditsMixIn.java View source code
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "media_type", defaultImpl = CreditBasic.class)
@JsonSubTypes({ @JsonSubTypes.Type(value = CreditMovieBasic.class, name = "movie"), @JsonSubTypes.Type(value = CreditTVBasic.class, name = "tv") })
@JsonSetter("cast")
public void setCast(List<CreditBasic> cast) {
// Mixin empty class
}
Example 12
Project: jersey-master  File: Jersey1199List.java View source code
// Jackson 1
@org.codehaus.jackson.annotate.JsonTypeInfo(use = org.codehaus.jackson.annotate.JsonTypeInfo.Id.NAME, include = org.codehaus.jackson.annotate.JsonTypeInfo.As.PROPERTY)
@org.codehaus.jackson.annotate.JsonSubTypes({ @org.codehaus.jackson.annotate.JsonSubTypes.Type(value = ColorHolder.class) })
// Jackson 2
@com.fasterxml.jackson.annotation.JsonTypeInfo(use = com.fasterxml.jackson.annotation.JsonTypeInfo.Id.NAME, include = com.fasterxml.jackson.annotation.JsonTypeInfo.As.PROPERTY)
@com.fasterxml.jackson.annotation.JsonSubTypes({ @com.fasterxml.jackson.annotation.JsonSubTypes.Type(value = ColorHolder.class) })
// JSON-B
@JsonbTypeAdapter(Jersey1199Test.JsonbObjectToColorHolderAdapter.class)
public Object[] getObjects() {
    return objects;
}
Example 13
Project: stampede-master  File: Backend.java View source code
@NotNull
@Valid
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({ @JsonSubTypes.Type(name = "postgres", value = Postgres.class) })
@JsonProperty(required = true)
public BackendImplementation getBackendImplementation() {
    return super.getBackendImplementation();
}