private static void initPropertyMap() { PROPERTY_MAP.put(BooleanProperty.class, SimpleType.constructUnsafe(Boolean.class)); PROPERTY_MAP.put(FloatProperty.class, SimpleType.constructUnsafe(Float.class)); PROPERTY_MAP.put(DoubleProperty.class, SimpleType.constructUnsafe(Double.class)); PROPERTY_MAP.put(DecimalProperty.class, SimpleType.constructUnsafe(BigDecimal.class)); PROPERTY_MAP.put(ByteProperty.class, SimpleType.constructUnsafe(Byte.class)); PROPERTY_MAP.put(ShortProperty.class, SimpleType.constructUnsafe(Short.class)); PROPERTY_MAP.put(IntegerProperty.class, SimpleType.constructUnsafe(Integer.class)); PROPERTY_MAP.put(BaseIntegerProperty.class, SimpleType.constructUnsafe(Integer.class)); PROPERTY_MAP.put(LongProperty.class, SimpleType.constructUnsafe(Long.class)); // stringProperty包含了enum的场景,并不一定是转化为string // 但是,如果统一走StringPropertyConverter则可以处理enum的场景 PROPERTY_MAP.put(StringProperty.class, SimpleType.constructUnsafe(String.class)); PROPERTY_MAP.put(DateProperty.class, SimpleType.constructUnsafe(LocalDate.class)); PROPERTY_MAP.put(DateTimeProperty.class, SimpleType.constructUnsafe(Date.class)); PROPERTY_MAP.put(ByteArrayProperty.class, SimpleType.constructUnsafe(byte[].class)); PROPERTY_MAP.put(FileProperty.class, SimpleType.constructUnsafe(Part.class)); }
@Override public JavaType handleUnknownTypeId(final DeserializationContext ctxt, final JavaType baseType, final String subTypeId, final TypeIdResolver idResolver, final String failureMsg) throws IOException { try { if (subTypeId.contains("org.jasig.")) { final String newTypeName = subTypeId.replaceAll("jasig", "apereo"); LOGGER.warn("Found legacy CAS JSON definition type identified as [{}]. " + "While CAS will attempt to convert the legacy definition to [{}] for the time being, " + "the definition SHOULD manually be upgraded to the new supported syntax", subTypeId, newTypeName); final Class newType = ClassUtils.getClass(newTypeName); return SimpleType.construct(newType); } return null; } catch (final Exception e) { throw Throwables.propagate(e); } }
@Override public Object deserializeTypedFromObject(final JsonParser jp, final DeserializationContext ctxt) throws IOException { JsonNode node = jp.readValueAsTree(); NamedDefinition res = NamedProviders.get((Class<NamedDefinition>) _baseType.getRawClass(), node.get("type").asText()); if (res == null) { return null; } JavaType type = SimpleType.construct(res.getClass()); JsonParser jsonParser = new TreeTraversingParser(node, jp.getCodec()); if (jsonParser.getCurrentToken() == null) { jsonParser.nextToken(); } JsonDeserializer<Object> deser = ctxt.findContextualValueDeserializer(type, _property); return deser.deserialize(jsonParser, ctxt); }
@Override public JavaType typeFromId(DatabindContext context, String id) { DeserializationContext ctx = (DeserializationContext) context; Map<String, Class> map = (Map) ctx.getAttribute("secucardobjectmap"); Class type = map.get(id); JavaType javatype; if (type == null) { javatype = MapType.construct(HashMap.class, SimpleType.construct(String.class), SimpleType.construct(Object.class)); } else { javatype = SimpleType.construct(type); } if (JsonToken.END_ARRAY.equals(ctx.getParser().getCurrentToken())) { // it is expected to get called here when reading the last token. javatype = CollectionType.construct(ArrayList.class, javatype); } return javatype; }
@Override public Set<PackageVersion> getRepoIndex(IRepoProvider provider) { RepoEntry indexEntry = provider.getEntry(IndexFileIndexer.INDEX_FILE); if (indexEntry != null) { if (!indexEntry.hasChanged(this.latest)) { return null; } this.latest = indexEntry; try { String indexString = StreamUtils.copyToString(provider.getEntryStream(IndexFileIndexer.INDEX_FILE), Charset.forName("UTF-8")); CollectionType indexType = CollectionType.construct(Set.class, SimpleType.construct(PackageVersion.class)); return this.mapper.readValue(indexString, indexType); } catch (IOException e) { throw new RuntimeException("Failed to read index", e); } } throw new RuntimeException("Didn't find index file"); }
private ObjectMapper getObjectMapper() { objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); // objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, // true); objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true); objectMapper.enableDefaultTypingAsProperty(DefaultTyping.JAVA_LANG_OBJECT, "_typeName"); TypeResolverBuilder<?> joynrTypeResolverBuilder = objectMapper.getSerializationConfig() .getDefaultTyper(SimpleType.construct(Object.class)); SimpleModule module = new SimpleModule("NonTypedModule", new Version(1, 0, 0, "", "", "")); module.addSerializer(new JoynrEnumSerializer()); module.addSerializer(new JoynrListSerializer()); TypeDeserializer typeDeserializer = joynrTypeResolverBuilder.buildTypeDeserializer(objectMapper.getDeserializationConfig(), SimpleType.construct(Object.class), null); module.addDeserializer(Object.class, new JoynrUntypedObjectDeserializer(typeDeserializer)); objectMapper.registerModule(module); return objectMapper; }
private ObjectMapper getObjectMapper() { objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); // objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, // true); objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true); objectMapper.enableDefaultTypingAsProperty(DefaultTyping.JAVA_LANG_OBJECT, "_typeName"); TypeResolverBuilder<?> joynrTypeResolverBuilder = objectMapper.getSerializationConfig() .getDefaultTyper(SimpleType.construct(Object.class)); return objectMapper; }
private AbstractType typeScriptTypeFromJavaType(Module module, Class<?> type) { if (type == boolean.class) { return BooleanType.getInstance(); } else if (type == int.class) { return NumberType.getInstance(); } else if (type == double.class) { return NumberType.getInstance(); } else if (type == String.class) { return StringType.getInstance(); } else if (type.isEnum()) { return tsJsonFormatVisitorWrapper.parseEnumOrGetFromCache(module, SimpleType .construct(type)); } else if (type.isArray()) { return new ArrayType(AnyType.getInstance()); } throw new UnsupportedOperationException(); }
/** * @param module * Module to be filled with named types (classes, enums, ...) * @param classes * Class for which generating definition * @throws JsonMappingException */ public Module generateTypeScript(String moduleName, Collection<? extends Class<?>> classes, Configuration conf) throws JsonMappingException { if(conf == null) { conf = new Configuration(); } Module module = new Module(moduleName); TSJsonFormatVisitorWrapper visitor = new TSJsonFormatVisitorWrapper(module, conf); for (Class<?> clazz : classes) { AbstractType customType = conf.getCustomTypes().get(clazz.getName()); if(customType != null && customType instanceof TypeDeclarationType) { // When the class is registered as TypeDeclarationType, then ... String tsTypeName = conf.getNamingStrategy().getName(SimpleType.construct(clazz)); // ... add that type to the module ... module.getNamedTypes().put(tsTypeName, (TypeDeclarationType)customType); // ... instead of inspecting class body continue; } mapper.acceptJsonFormatVisitor(clazz, visitor); } return module; }
@Test public void modules() { NumberSerializer serializer1 = new NumberSerializer(Integer.class); SimpleModule module = new SimpleModule(); module.addSerializer(Integer.class, serializer1); ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().modules(module).build(); Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next(); assertSame(serializer1, serializers.findSerializer(null, SimpleType.construct(Integer.class), null)); }
@Test @SuppressWarnings("unchecked") public void modulesToInstallByClass() { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().modulesToInstall(CustomIntegerModule.class).build(); Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next(); assertSame(CustomIntegerSerializer.class, serializers.findSerializer(null, SimpleType.construct(Integer.class), null).getClass()); }
@Test public void serializerByType() { JsonSerializer<Number> serializer = new NumberSerializer(Integer.class); ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json() .modules(new ArrayList<>()) // Disable well-known modules detection .serializerByType(Boolean.class, serializer).build(); assertTrue(getSerializerFactoryConfig(objectMapper).hasSerializers()); Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next(); assertSame(serializer, serializers.findSerializer(null, SimpleType.construct(Boolean.class), null)); }
@Test public void deserializerByType() throws JsonMappingException { JsonDeserializer<Date> deserializer = new DateDeserializers.DateDeserializer(); ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json() .modules(new ArrayList<>()) // Disable well-known modules detection .deserializerByType(Date.class, deserializer).build(); assertTrue(getDeserializerFactoryConfig(objectMapper).hasDeserializers()); Deserializers deserializers = getDeserializerFactoryConfig(objectMapper).deserializers().iterator().next(); assertSame(deserializer, deserializers.findBeanDeserializer(SimpleType.construct(Date.class), null, null)); }
@Test public void setModules() { NumberSerializer serializer = new NumberSerializer(Integer.class); SimpleModule module = new SimpleModule(); module.addSerializer(Integer.class, serializer); this.factory.setModules(Arrays.asList(new Module[]{module})); this.factory.afterPropertiesSet(); ObjectMapper objectMapper = this.factory.getObject(); Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next(); assertSame(serializer, serializers.findSerializer(null, SimpleType.construct(Integer.class), null)); }
@Override public void setupModule(SetupContext context) { // Modify the Map serializer to the delegate if it matches Map<String, ?> context.addBeanSerializerModifier(new BeanSerializerModifier() { @Override public JsonSerializer<?> modifyMapSerializer(SerializationConfig config, MapType valueType, BeanDescription beanDesc, JsonSerializer<?> serializer) { if (valueType.getKeyType().equals(SimpleType.construct(String.class))) { return new DelegatingMapSerializer(serializer); } return serializer; } }); }
private SwaggerReader(Swagger swagger) { this.swagger = swagger; ModelConverters.getInstance().addConverter(new ModelResolver(Json.mapper()) { protected boolean shouldIgnoreClass(Type type) { if (type instanceof SimpleType && JSONObject.class.equals(((SimpleType)type).getRawClass())) { return true; } return super.shouldIgnoreClass(type); } }); }
@Override public JavaType typeFromId(String id) { requireNonNull(id, "id is null"); Class<?> typeClass = classResolver.apply(id); checkArgument(typeClass != null, "Unknown type ID: %s", id); return SimpleType.construct(typeClass); }
@Override public JavaType modifyType(JavaType type, Type jdkType, TypeBindings context, TypeFactory typeFactory) { try { if (type.getClass().isAssignableFrom(SimpleType.class)) { Object overriddenBean = applicationContext.getBean(type.getRawClass().getName()); return SimpleType.construct(overriddenBean.getClass()); } } catch (NoSuchBeanDefinitionException e) { LOG.debug("No configured bean for " + type.getClass().getName() + " returning original type"); } return type; }
@Override public JavaType typeFromId(DatabindContext context, String id) { Class<?> clazz = basicMetaData.getTypeClass(id); if (clazz == null) { return null; } JavaType javaType = SimpleType.construct(clazz); return javaType; }
@Theory public void objectMapperWithTTKeyDeserializerInstalledYieldsExpectedDeserializationsForTTs(Pair<String, Object> serializedAndExpectedDeserialization) throws IOException { final ObjectMapper om = new ObjectMapper(); om.registerModule(new KeyDeserializersOnlyModule()); final String serialzied = serializedAndExpectedDeserialization.fst; final Object expected = serializedAndExpectedDeserialization.snd; final JavaType mapType = MapType.construct(HashMap.class, SimpleType.construct(serializedAndExpectedDeserialization.snd.getClass()), SimpleType.construct(Void.class)); final Object got = ((Map)om.readValue(asJsonMapKey(serialzied), mapType)).keySet().iterator().next(); Assert.assertEquals(got, expected); }
public static <T> T decode(InputStream jsonStream, SimpleType typeInfo) { try { return mapper.readValue(jsonStream, typeInfo); } catch (IOException e) { throw new RuntimeException("Can't serialize object", e); } }
@Override public JavaType typeFromId(DatabindContext context, String id) { try { return SimpleType.constructUnsafe(Class.forName(getClass().getPackage().getName() + "." + id.substring(0, 1).toUpperCase() + id.substring(1))); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } }
@Override public JsonDeserializer<?> findBeanDeserializer(JavaType type, DeserializationConfig config, BeanDescription beanDesc) throws JsonMappingException { if (Tuple2.class.isAssignableFrom(type.getRawClass())) { SimpleType simple = (SimpleType) type; return new Tuple2Deserializer(simple.containedType(0), simple.containedType(1)); } return null; }
/** * Creates a new default request builder without actual parameters * * @param transport transport for request performing * @param mapper mapper for JSON processing */ public RequestBuilder(@NotNull Transport transport, @NotNull ObjectMapper mapper) { super(transport, mapper); id = NullNode.instance; objectParams = mapper.createObjectNode(); arrayParams = mapper.createArrayNode(); method = ""; javaType = SimpleType.construct(Object.class); }
@BeforeClass public static void init() throws Exception { userMapper.registerModule(new GuavaModule()); testData = new ObjectMapper().readValue( Resources.toString(JsonRpcServiceTest.class.getResource("/test_data.json"), Charsets.UTF_8), MapType.construct(Map.class, SimpleType.construct(String.class), SimpleType.construct(RequestResponse.class))); }
@Test(expected = IllegalArgumentException.class) public void testByteConversion() { ObjectMapper mapper = new JSONBindingFactory().createBaseObjectMapper(); JsonNode paramValue = new IntNode(128); JavaType javaType = SimpleType.construct(byte.class); mapper.convertValue(paramValue, javaType); }
public JsonMessageSerializerModule() { objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); objectMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true); // objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true); objectMapper.enableDefaultTypingAsProperty(DefaultTyping.JAVA_LANG_OBJECT, "_typeName"); TypeResolverBuilder<?> joynrTypeResolverBuilder = objectMapper.getSerializationConfig() .getDefaultTyper(SimpleType.construct(Object.class)); SimpleModule module = new SimpleModule("NonTypedModule", new Version(1, 0, 0, "", "", "")); module.addSerializer(new JoynrEnumSerializer()); module.addSerializer(new JoynrListSerializer()); module.addSerializer(new JoynrArraySerializer()); TypeDeserializer typeDeserializer = joynrTypeResolverBuilder.buildTypeDeserializer(objectMapper.getDeserializationConfig(), SimpleType.construct(Object.class), null); module.addDeserializer(Request.class, new RequestDeserializer(objectMapper)); module.addDeserializer(OneWayRequest.class, new OneWayRequestDeserializer(objectMapper)); module.addDeserializer(Object.class, new JoynrUntypedObjectDeserializer(typeDeserializer)); module.setMixInAnnotation(Throwable.class, ThrowableMixIn.class); objectMapper.registerModule(module); }
/** * 生成java type * @param parameter method parameter * @return java type */ private JavaType generateJavaType(MethodParameter parameter) { Class<?> parameterClass = parameter.getParameterType(); Class<?> genericClass = getGenericType(parameterClass, parameter); if (Objects.isNull(genericClass)) { return SimpleType.constructUnsafe(parameterClass); } return OBJECT_MAPPER.getTypeFactory().constructParametricType(parameter.getParameterType(), genericClass); }
public ExtendedJsonSerializer() { super(SimpleType.constructUnsafe(ExtendedJsonWrapper.class), null, new BeanPropertyWriter[0], new BeanPropertyWriter[0]); }
@Test public void modulesToInstallByInstance() { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().modulesToInstall(new CustomIntegerModule()).build(); Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next(); assertSame(CustomIntegerSerializer.class, serializers.findSerializer(null, SimpleType.construct(Integer.class), null).getClass()); }
@Test public void completeSetup() { NopAnnotationIntrospector annotationIntrospector = NopAnnotationIntrospector.instance; ObjectMapper objectMapper = new ObjectMapper(); this.factory.setObjectMapper(objectMapper); assertTrue(this.factory.isSingleton()); assertEquals(ObjectMapper.class, this.factory.getObjectType()); Map<Class<?>, JsonDeserializer<?>> deserializers = new HashMap<Class<?>, JsonDeserializer<?>>(); deserializers.put(Date.class, new DateDeserializer()); JsonSerializer<Class<?>> serializer1 = new ClassSerializer(); JsonSerializer<Number> serializer2 = new NumberSerializer(Integer.class); // Disable well-known modules detection this.factory.setModules(new ArrayList<>()); this.factory.setSerializers(serializer1); this.factory.setSerializersByType(Collections.singletonMap(Boolean.class, serializer2)); this.factory.setDeserializersByType(deserializers); this.factory.setAnnotationIntrospector(annotationIntrospector); this.factory.setFeaturesToEnable(SerializationFeature.FAIL_ON_EMPTY_BEANS, DeserializationFeature.UNWRAP_ROOT_VALUE, JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS); this.factory.setFeaturesToDisable(MapperFeature.AUTO_DETECT_GETTERS, MapperFeature.AUTO_DETECT_FIELDS, JsonParser.Feature.AUTO_CLOSE_SOURCE, JsonGenerator.Feature.QUOTE_FIELD_NAMES); assertFalse(getSerializerFactoryConfig(objectMapper).hasSerializers()); assertFalse(getDeserializerFactoryConfig(objectMapper).hasDeserializers()); this.factory.setSerializationInclusion(Include.NON_NULL); this.factory.afterPropertiesSet(); assertSame(objectMapper, this.factory.getObject()); assertTrue(getSerializerFactoryConfig(objectMapper).hasSerializers()); assertTrue(getDeserializerFactoryConfig(objectMapper).hasDeserializers()); Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next(); assertSame(serializer1, serializers.findSerializer(null, SimpleType.construct(Class.class), null)); assertSame(serializer2, serializers.findSerializer(null, SimpleType.construct(Boolean.class), null)); assertNull(serializers.findSerializer(null, SimpleType.construct(Number.class), null)); assertSame(annotationIntrospector, objectMapper.getSerializationConfig().getAnnotationIntrospector()); assertSame(annotationIntrospector, objectMapper.getDeserializationConfig().getAnnotationIntrospector()); assertTrue(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)); assertTrue(objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); assertTrue(objectMapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)); assertTrue(objectMapper.getFactory().isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)); assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS)); assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)); assertFalse(objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS)); assertFalse(objectMapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)); assertFalse(objectMapper.getFactory().isEnabled(JsonGenerator.Feature.QUOTE_FIELD_NAMES)); assertSame(Include.NON_NULL, objectMapper.getSerializationConfig().getSerializationInclusion()); }
public JsonType(Class clazz, boolean isBinary) { this(SimpleType.construct(clazz), isBinary); }
public void setParameterValues(Properties parameters) { Class<?> clazz = ParametrizedJsonTypes.getClassParameter("type", parameters, "java.lang.", Object.class); boolean binary = !"false".equals(parameters.get("binary")); init(SimpleType.construct(clazz), binary); }
public InternalTypeDeserializer(Class<T> baseClass, TypeIdResolver typeIdResolver) { super(baseClass); this.typeDeserializer = new AsPropertyTypeDeserializer(SimpleType.construct(baseClass), typeIdResolver, TYPE_PROPERTY, false, null); }
public List<Map<String, Object>> transformJsonToList(String json) throws IOException { JavaType javaType = MapType.construct(HashMap.class, SimpleType.construct(String.class), SimpleType.construct(Object.class)); CollectionType listType = TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, javaType); return mapper.readValue(json, listType); }
/** * Sets an expected return type for a request * * @param id request id * @param responseType expected response type * @return a new builder */ private BatchRequestBuilder<K, V> returnType(Object id, @NotNull Class<?> responseType) { returnTypes.put(id, SimpleType.construct(responseType)); return this; }
/** * Sets an expected response type of requests. * This method is preferred when requests have the same response type. * * @param valuesClass expected requests return type * @param <NV> expected requests return type * @return a new builder */ public <NV> BatchRequestBuilder<K, NV> returnType(@NotNull Class<NV> valuesClass) { return new BatchRequestBuilder<K, NV>(transport, mapper, requests, returnTypes, keysType, SimpleType.construct(valuesClass)); }
/** * Sets expected return type. This method is suitable for non-generic types * * @param responseType expected return type * @param <NT> new return type * @return new builder */ @NotNull public <NT> RequestBuilder<NT> returnAs(@NotNull Class<NT> responseType) { return new RequestBuilder<NT>(transport, mapper, method, id, objectParams, arrayParams, SimpleType.construct(responseType)); }