当前位置: 首页>>代码示例>>Java>>正文


Java TypeFactory类代码示例

本文整理汇总了Java中com.fasterxml.jackson.databind.type.TypeFactory的典型用法代码示例。如果您正苦于以下问题:Java TypeFactory类的具体用法?Java TypeFactory怎么用?Java TypeFactory使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


TypeFactory类属于com.fasterxml.jackson.databind.type包,在下文中一共展示了TypeFactory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: createMapper

import com.fasterxml.jackson.databind.type.TypeFactory; //导入依赖的package包/类
private ObjectMapper createMapper(JsonFactory mapping, ClassLoader classLoader) {
    ObjectMapper mapper = new ObjectMapper(mapping);
    mapper.addMixIn(MasterSlaveServersConfig.class, MasterSlaveServersConfigMixIn.class);
    mapper.addMixIn(SingleServerConfig.class, SingleSeverConfigMixIn.class);
    mapper.addMixIn(Config.class, ConfigMixIn.class);
    mapper.addMixIn(CodecProvider.class, ClassMixIn.class);
    mapper.addMixIn(ResolverProvider.class, ClassMixIn.class);
    mapper.addMixIn(Codec.class, ClassMixIn.class);
    mapper.addMixIn(RedissonNodeInitializer.class, ClassMixIn.class);
    mapper.addMixIn(LoadBalancer.class, ClassMixIn.class);
    FilterProvider filterProvider = new SimpleFilterProvider()
            .addFilter("classFilter", SimpleBeanPropertyFilter.filterOutAllExcept());
    mapper.setFilterProvider(filterProvider);
    mapper.setSerializationInclusion(Include.NON_NULL);

    if (classLoader != null) {
        TypeFactory tf = TypeFactory.defaultInstance()
                .withClassLoader(classLoader);
        mapper.setTypeFactory(tf);
    }
    
    return mapper;
}
 
开发者ID:qq1588518,项目名称:JRediClients,代码行数:24,代码来源:ConfigSupport.java

示例2: fetchAll

import com.fasterxml.jackson.databind.type.TypeFactory; //导入依赖的package包/类
@Override
public ListResult<T> fetchAll() {
    try {
        // get the data out..
        byte[] json = jsondb.getAsByteArray(getCollectionPath());
        if( json!=null && json.length > 0 ) {

            // Lets use jackson to parse the map of keys to our model instances
            ObjectMapper mapper = Json.mapper();
            TypeFactory typeFactory = mapper.getTypeFactory();
            MapType mapType = typeFactory.constructMapType(LinkedHashMap.class, String.class, getType());
            LinkedHashMap<String, T> map = mapper.readValue(json, mapType);

            return ListResult.of(map.values());
        }

        return ListResult.of(Collections.<T>emptyList());
    } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") RuntimeException|IOException e) {
        throw SyndesisServerException.launderThrowable(e);
    }
}
 
开发者ID:syndesisio,项目名称:syndesis,代码行数:22,代码来源:JsonDbDao.java

示例3: constructList

import com.fasterxml.jackson.databind.type.TypeFactory; //导入依赖的package包/类
/**
 * Constructs the object based on the content as a List, the JSON can be an array or just a single value without the [] symbols
 * @param content Reader
 * @return A collection of the specified type
 */
public <T> List<T> constructList(Reader content, Class<T> requiredType)
{
    ObjectReader reader = objectMapper.readerFor(TypeFactory.defaultInstance().constructParametricType(List.class, requiredType));
    try
    {
        List<T> toReturn = reader.readValue(content);
        if (toReturn == null || toReturn.isEmpty())
        {
          throw new InvalidArgumentException("Could not read content from HTTP request body, the list is empty");
        }
        return toReturn;
    }
    catch (IOException error)
    {
        throw new InvalidArgumentException("Could not read content from HTTP request body: "+error.getMessage());
    }
}
 
开发者ID:Alfresco,项目名称:alfresco-remote-api,代码行数:23,代码来源:JacksonHelper.java

示例4: buildConfigurationDeserializer

import com.fasterxml.jackson.databind.type.TypeFactory; //导入依赖的package包/类
private JsonDeserializer<io.redlink.smarti.model.config.Configuration > buildConfigurationDeserializer(ObjectMapper objectMapper) {
    return new JsonDeserializer<io.redlink.smarti.model.config.Configuration>() {
        @Override
        public io.redlink.smarti.model.config.Configuration deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {

            final TypeFactory tf = ctxt.getTypeFactory();
            final MapLikeType smartiConfigType = tf.constructMapLikeType(Map.class,
                    tf.constructType(String.class),
                    tf.constructCollectionLikeType(List.class,
                            ComponentConfiguration.class));

            final io.redlink.smarti.model.config.Configuration configuration = new io.redlink.smarti.model.config.Configuration();
            configuration.setConfig(objectMapper.readerFor(smartiConfigType).readValue(p, smartiConfigType));
            return configuration;
        }

    };
}
 
开发者ID:redlink-gmbh,项目名称:smarti,代码行数:19,代码来源:RestServiceConfiguration.java

示例5: fromJsonAsMap

import com.fasterxml.jackson.databind.type.TypeFactory; //导入依赖的package包/类
@SuppressWarnings( "unchecked" )
public static < K, V > Map< K, V > fromJsonAsMap (
		String jsonToken,
		Class< K > typeClassK,
		Class< V > typeClassV
                                                 ) {
	
	Map< K, V > asMap = null;
	
	try {
		
		JavaType collectionType = TypeFactory
				.defaultInstance ()
				.constructMapType ( Map.class, typeClassK, typeClassV );
		
		asMap = mapper.readValue ( jsonToken, collectionType );
		
	} catch ( IOException e ) {
		e.printStackTrace ();
	}
	return asMap;
}
 
开发者ID:akimaleo,项目名称:JavaREST-WorldHistoryTracker,代码行数:23,代码来源:JacksonConverter.java

示例6: getBeanCollectionFromJsonString

import com.fasterxml.jackson.databind.type.TypeFactory; //导入依赖的package包/类
public static <T> List<T> getBeanCollectionFromJsonString( String json, Class<T> class_name )
{
    List<T> contents = null;
    try
    {
        contents =
            getDefaultMapper().readValue( json,
                                          TypeFactory.defaultInstance().constructCollectionType( List.class,
                                                                                                 class_name ) );
    }
    catch ( IOException e )
    {
        logger.error( "Exception in getBeanCollectionFromJsonString", e );
    }

    return contents;
}
 
开发者ID:vmware,项目名称:OHMS,代码行数:18,代码来源:JsonUtils.java

示例7: tryMatchRedfishResource

import com.fasterxml.jackson.databind.type.TypeFactory; //导入依赖的package包/类
private JavaType tryMatchRedfishResource( String id )
{
    Matcher resourceMatcher = REDFISH_RESOURCE.matcher( id );
    if ( resourceMatcher.matches() )
    {
        try
        {
            String redfishResourceClassName = getClassName( resourceMatcher.group( REDFISH_RESOURCE_NAME_GROUP ) );
            Class detectedClass = Class.forName( redfishResourceClassName );
            return TypeFactory.defaultInstance().constructSpecializedType( baseType, detectedClass );
        }
        catch ( ClassNotFoundException e )
        {
            throw new UnsupportedOperationException(
                "Could not determine class to deserialize into for \"@odata.type\": \"" + id + "\"" );
        }
    }
    return null;
}
 
开发者ID:vmware,项目名称:OHMS,代码行数:20,代码来源:OdataTypeResolver.java

示例8: testExtraction

import com.fasterxml.jackson.databind.type.TypeFactory; //导入依赖的package包/类
@Test
public void testExtraction() throws Exception {
	Message<?> received = messageCollector.forChannel(source.output()).poll(10, TimeUnit.SECONDS);
	assertNotNull(received);
	assertThat(received.getPayload(), Matchers.instanceOf(String.class));


	CollectionLikeType valueType = TypeFactory.defaultInstance()
			.constructCollectionLikeType(List.class, Map.class);

	List<Map<?, ?>> payload = this.objectMapper.readValue((String) received.getPayload(), valueType);

	assertEquals(3, payload.size());
	assertEquals(1, payload.get(0).get("ID"));
	assertEquals("John", payload.get(2).get("NAME"));
}
 
开发者ID:spring-cloud-stream-app-starters,项目名称:jdbc,代码行数:17,代码来源:JdbcSourceIntegrationTests.java

示例9: deserializeJsonStr

import com.fasterxml.jackson.databind.type.TypeFactory; //导入依赖的package包/类
/**
 * Helper method for deserializing a chat JSON response to a collection of objects.
 *
 * @param jsonStr
 *            The chat JSON response.
 * @param mapElement
 *            Chat JSON responses are actually maps with a single element. This argument is
 *            the value of the element to pull out from the map.
 * @param colClassElements
 *            The types of objects that the collection object will contain.
 * @param objMapper
 *            The JSON object mapper used to deserialize the JSON string.
 * @return A collection of elements of type <code>colClassElements</code>.
 */
private <T> Collection<T> deserializeJsonStr(String jsonStr, String mapElement,
                                             Class<T> colClassElements,
                                             ObjectMapper objMapper) {
    Map<String, Collection<T>> re;
    try {
        TypeFactory typeFactory = objMapper.getTypeFactory();
        CollectionType type = typeFactory.constructCollectionType(List.class, colClassElements);
        MapType thetype = typeFactory.constructMapType(HashMap.class,
                                                       typeFactory.constructType(String.class),
                                                       type);
        re = objMapper.readValue(jsonStr, thetype);
    } catch (IOException e) {
        LOG.error("Got exception when trying to deserialize list of {}", colClassElements, e);
        return Lists.newArrayListWithExpectedSize(0);
    }
    return re.get(mapElement);
}
 
开发者ID:OpenChatAlytics,项目名称:OpenChatAlytics,代码行数:32,代码来源:JsonHipChatDAO.java

示例10: getPropertyAs

import com.fasterxml.jackson.databind.type.TypeFactory; //导入依赖的package包/类
@Override
public <T> Optional<T> getPropertyAs(final String name, final Type type) throws IllegalArgumentException {
    final Optional<String> property = getProperty(name);
    if (!property.isPresent()) {
        return Optional.empty();
    }
    try {
        final TypeFactory typeFactory = _objectMapper.getTypeFactory();
        @SuppressWarnings("unchecked")
        final Optional<T> value = Optional.ofNullable((T) _objectMapper.readValue(
                property.get(),
                typeFactory.constructType(type)));
        return value;
    } catch (final IOException e) {
        throw new IllegalArgumentException(
                String.format(
                        "Unable to construct object from configuration; name=%s, type=%s, property=%s",
                        name,
                        type,
                        property),
                e);
    }
}
 
开发者ID:ArpNetworking,项目名称:metrics-aggregator-daemon,代码行数:24,代码来源:BaseJacksonConfiguration.java

示例11: getAs

import com.fasterxml.jackson.databind.type.TypeFactory; //导入依赖的package包/类
@Override
public <T> Optional<T> getAs(final Type type) throws IllegalArgumentException {
    final Optional<JsonNode> property = getJsonSource().getValue();
    if (!property.isPresent()) {
        return Optional.empty();
    }
    try {
        final TypeFactory typeFactory = _objectMapper.getTypeFactory();
        @SuppressWarnings("unchecked")
        final Optional<T> value = Optional.ofNullable((T) _objectMapper.readValue(
                _objectMapper.treeAsTokens(property.get()), typeFactory.constructType(type)));
        return value;
    } catch (final IOException e) {
        throw new IllegalArgumentException(
                String.format(
                        "Unable to construct object from configuration; type=%s, property=%s",
                        type,
                        property),
                e);
    }
}
 
开发者ID:ArpNetworking,项目名称:metrics-aggregator-daemon,代码行数:22,代码来源:BaseJacksonConfiguration.java

示例12: testSegmenter

import com.fasterxml.jackson.databind.type.TypeFactory; //导入依赖的package包/类
@Test
public void testSegmenter() throws IOException {
	String[] args = { "-input", "/home/rishi/Desktop/testDoc/To check/paper 2009-Semantic interpretation and knowledge extraction.pdf",
			"-format", "STDOUT" };
	
	String heading = "Semantic interpretation and knowledge extraction ";

	Params cliParams = Params.getParams(args);
	ObjectMapper mapper = new ObjectMapper();

	String path = cliParams.getInput();
	PdfSections pdf2Xml = new PdfSections(cliParams);
	pdf2Xml.processFile(path);
	List<Structure> structure = mapper.readValue(pdf2Xml.generateOutput().get(0), TypeFactory.defaultInstance().constructCollectionType(List.class, Structure.class));
	Assert.assertTrue(structure.get(0).getHeading().equals(heading));
	
}
 
开发者ID:TekstoSense,项目名称:pdf-segmenter,代码行数:18,代码来源:SegmenterTest.java

示例13: getChangedContainers

import com.fasterxml.jackson.databind.type.TypeFactory; //导入依赖的package包/类
private Map<String, ContainerQuota> getChangedContainers( final String quotaContainers ) throws java.io.IOException
{
    Map<String, ContainerQuota> changedContainersFiltered = new HashMap<>();
    TypeFactory typeFactory = mapper.getTypeFactory();
    CollectionType arrayType = typeFactory.constructCollectionType( ArrayList.class, ChangedContainerDto.class );
    List<ChangedContainerDto> changedContainers = mapper.readValue( quotaContainers, arrayType );
    for ( ChangedContainerDto cont : changedContainers )
    {
        ContainerQuotaDto containerQuotaDto = cont.getQuota();
        ContainerSize containerSize = containerQuotaDto.getContainerSize();
        ContainerQuota defaultQuota = ContainerSize.getDefaultContainerQuota( containerSize );
        if ( containerSize == ContainerSize.CUSTOM )
        {
            defaultQuota = containerQuotaDto.getContainerQuota();
        }

        changedContainersFiltered.put( cont.getHostId(), defaultQuota );
    }
    return changedContainersFiltered;
}
 
开发者ID:subutai-io,项目名称:base,代码行数:21,代码来源:RestServiceImpl.java

示例14: generateValueType

import com.fasterxml.jackson.databind.type.TypeFactory; //导入依赖的package包/类
/**
 * Generates a {@link JavaType} that matches the target Thrift field represented by the provided
 * {@code <E>} enumerated value.  If the field's type includes generics, the generics will
 * be added to the generated {@link JavaType} to support proper conversion.
 * @param thriftInstance The Thrift-generated class instance that will be converted to/from JSON.
 * @param field A {@code <E>} enumerated value that represents a field in a Thrift-based entity.
 * @return The {@link JavaType} representation of the type associated with the field.
 * @throws NoSuchFieldException if unable to determine the field's type.
 * @throws SecurityException if unable to determine the field's type.
 */
protected JavaType generateValueType(final T thriftInstance, final E field) throws NoSuchFieldException, SecurityException {
    final TypeFactory typeFactory = TypeFactory.defaultInstance();

    final Field declaredField = thriftInstance.getClass().getDeclaredField(field.getFieldName());
    if(declaredField.getType().equals(declaredField.getGenericType())) {
        log.debug("Generating JavaType for type '{}'.", declaredField.getType());
        return typeFactory.constructType(declaredField.getType());
    } else {
        final ParameterizedType type = (ParameterizedType)declaredField.getGenericType();
        final Class<?>[] parameterizedTypes = new Class<?>[type.getActualTypeArguments().length];
        for(int i=0; i<type.getActualTypeArguments().length; i++) {
            parameterizedTypes[i] = (Class<?>)type.getActualTypeArguments()[i];
        }
        log.debug("Generating JavaType for type '{}' with generics '{}'", declaredField.getType(), parameterizedTypes);
        return typeFactory.constructParametricType(declaredField.getType(), parameterizedTypes);
    }
}
 
开发者ID:SciGaP,项目名称:allocateme,代码行数:28,代码来源:AbstractThriftDeserializer.java

示例15: parse

import com.fasterxml.jackson.databind.type.TypeFactory; //导入依赖的package包/类
private <T> T parse(JsonNode node, ValueType<T> valueType) throws IOException {
    JavaType javaType = null;
    if (valueType instanceof SimpleType) {
        SimpleType simpleType = (SimpleType) valueType;
        javaType = TypeFactory.defaultInstance().uncheckedSimpleType(simpleType.getBaseClass());
    } else if (valueType instanceof GenericType) {
        GenericType genericType = (GenericType) valueType;
        javaType = TypeFactory.defaultInstance().constructParametricType(genericType.getBaseClass(), genericType.getParameterTypes());
    } else if (valueType instanceof CollectionType) {
        CollectionType collectionType = (CollectionType) valueType;
        javaType = TypeFactory.defaultInstance().constructCollectionType(collectionType.getBaseClass(), collectionType.getElementClass());
    } else if (valueType instanceof MapType) {
        MapType mapType = (MapType) valueType;
        javaType = TypeFactory.defaultInstance().constructMapType(mapType.getBaseClass(), mapType.getKeyClass(), mapType.getValueClass());
    } else {
        throw new IllegalArgumentException("Unexpected class instance encountered: " + valueType.getClass());
    }
    return (T) parse(node, javaType);
}
 
开发者ID:Qubite,项目名称:tomoko,代码行数:20,代码来源:JacksonTreeParser.java


注:本文中的com.fasterxml.jackson.databind.type.TypeFactory类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。