本文整理汇总了Java中com.fasterxml.jackson.annotation.JsonTypeInfo类的典型用法代码示例。如果您正苦于以下问题:Java JsonTypeInfo类的具体用法?Java JsonTypeInfo怎么用?Java JsonTypeInfo使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
JsonTypeInfo类属于com.fasterxml.jackson.annotation包,在下文中一共展示了JsonTypeInfo类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: addJsonTypeInfo
import com.fasterxml.jackson.annotation.JsonTypeInfo; //导入依赖的package包/类
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);
}
}
示例2: getObjectMapper
import com.fasterxml.jackson.annotation.JsonTypeInfo; //导入依赖的package包/类
@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;
}
示例3: home
import com.fasterxml.jackson.annotation.JsonTypeInfo; //导入依赖的package包/类
@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);
}
示例4: processSubTypeRule
import com.fasterxml.jackson.annotation.JsonTypeInfo; //导入依赖的package包/类
@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());
}
示例5: resolveJsonType
import com.fasterxml.jackson.annotation.JsonTypeInfo; //导入依赖的package包/类
@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;
}
示例6: saveType
import com.fasterxml.jackson.annotation.JsonTypeInfo; //导入依赖的package包/类
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);
}
示例7: testRoot
import com.fasterxml.jackson.annotation.JsonTypeInfo; //导入依赖的package包/类
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());
}
}
示例8: ServerConnection
import com.fasterxml.jackson.annotation.JsonTypeInfo; //导入依赖的package包/类
/**
* 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);
}
示例9: configureObjectMapper
import com.fasterxml.jackson.annotation.JsonTypeInfo; //导入依赖的package包/类
/**
* 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);
}
示例10: getJsonTypeInfoAnnotation
import com.fasterxml.jackson.annotation.JsonTypeInfo; //导入依赖的package包/类
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;
}
示例11: getJsonTypePropertyString
import com.fasterxml.jackson.annotation.JsonTypeInfo; //导入依赖的package包/类
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;
}
示例12: serializeWithType
import com.fasterxml.jackson.annotation.JsonTypeInfo; //导入依赖的package包/类
@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);
}
}
示例13: extractMetadata
import com.fasterxml.jackson.annotation.JsonTypeInfo; //导入依赖的package包/类
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();
}
示例14: buildTypeSerializer
import com.fasterxml.jackson.annotation.JsonTypeInfo; //导入依赖的package包/类
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);
}
示例15: buildTypeDeserializer
import com.fasterxml.jackson.annotation.JsonTypeInfo; //导入依赖的package包/类
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);
}