欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

实例演示:在Java中运用CollectionType类

最编程 2024-07-26 09:33:20
...

实例1: updateTenants

import com.fasterxml.jackson.databind.type.CollectionType; //导入依赖的package包/类
@SneakyThrows
private void updateTenants(String key, String config) {
    log.info("Tenants list was updated");

    if (!TENANTS_LIST_CONFIG_KEY.equals(key)) {
        throw new IllegalArgumentException("Wrong config key to update " + key);
    }

    assertExistsTenantsListConfig(config);

    CollectionType setType = defaultInstance().constructCollectionType(HashSet.class, TenantState.class);
    MapType type = defaultInstance().constructMapType(HashMap.class, defaultInstance().constructType(String.class), setType);
    Map<String, Set<TenantState>> tenantsByServiceMap = objectMapper.readValue(config, type);
    Set<TenantState> tenantKeys = tenantsByServiceMap.get(applicationName);

    assertExistTenants(tenantKeys);

    this.tenants = tenantKeys;
    this.suspendedTenants = tenantKeys.stream().filter(tenant -> SUSPENDED_STATE.equals(tenant.getState()))
        .map(TenantState::getName).collect(Collectors.toSet());
}
 

实例2: updateTenants

import com.fasterxml.jackson.databind.type.CollectionType; //导入依赖的package包/类
@SneakyThrows
private void updateTenants(String config)  {
    log.info("Tenants list was updated");

    CollectionType setType = defaultInstance().constructCollectionType(HashSet.class, TenantState.class);
    MapType type = defaultInstance().constructMapType(HashMap.class, defaultInstance().constructType(String.class), setType);
    Map<String, Set<TenantState>> tenantsByServiceMap = objectMapper.readValue(config, type);

    final Map<String, String> tenants = new HashMap<>();
    for (TenantState tenant: tenantsByServiceMap.getOrDefault(applicationName, emptySet())) {
        for (String host : hosts) {
            tenants.put(tenant.getName() + "." + host, tenant.getName().toUpperCase());
        }
    }

    this.tenants = tenants;
}
 

实例3: deserializeWithRetry

import com.fasterxml.jackson.databind.type.CollectionType; //导入依赖的package包/类
private Collection<Object> deserializeWithRetry(JsonParser p, DeserializationContext ctxt, JavaType contentType) throws IOException {
    final CollectionType collectionType = ctxt.getTypeFactory().constructCollectionType(Collection.class, contentType);

    try {
        return p.getCodec().readValue(p, collectionType);

    } catch (JsonMappingException e) {
        // attempt to read the value as string
        final String escapedString = p.getValueAsString();

        // stop here if value could not be read
        if (isNull(escapedString)) {
            throw ctxt.instantiationException(Collection.class, "Read null value when attempting to deserialize " + collectionType.toString());
        }

        // un-escape double quotes
        String unescapedString = escapedString.replaceAll("\"", "\"");

        // and attempt to parse again
        return new ObjectMapper().readValue(unescapedString, collectionType);
    }
}
 

实例4: fromJson

import com.fasterxml.jackson.databind.type.CollectionType; //导入依赖的package包/类
/**
 * 反序列化复杂Collection如List<Bean>
 *
 * @param <L>             the type parameter
 * @param <E>             the type parameter
 * @param jsonString      the json string
 * @param collectionClass the collection class
 * @param elementClass    the element class
 * @return 转换失败时返回 null
 */
public static <L extends Collection<E>, E> L fromJson(String jsonString,
                                                      Class<L> collectionClass,
                                                      Class<E> elementClass) {
    if (!StringUtils.hasText(jsonString)) {
        return null;
    }
    try {
        CollectionType type = mapper.getTypeFactory().constructCollectionType(collectionClass,
                elementClass);
        return mapper.readValue(jsonString, type);
    } catch (Exception e) {
        (new JsonUtil()).logger.error(e.getMessage(), e);
        return null;
    }
}
 

推荐阅读