com.fasterxml.jackson.databind.type.MapType源码实例Demo

类com.fasterxml.jackson.databind.type.MapType源码实例Demo

下面列出了com.fasterxml.jackson.databind.type.MapType 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: vividus   文件: KnownIssueProvider.java
private void loadKnownIssueIdentifiers() throws IOException
{
    String locationPattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + fileName;
    Resource[] resources = applicationContext.getResources(locationPattern);
    if (resources.length > 0)
    {
        ObjectMapper objectMapper = ObjectMapperFactory.createWithCaseInsensitiveEnumDeserializer();
        MapType mapType = objectMapper.getTypeFactory().constructMapType(Map.class, String.class,
                BddKnownIssueIdentifier.class);
        for (Resource resource : resources)
        {
            LOGGER.debug("Loading known issue identifiers from {}", resource.getDescription());
            knownIssueIdentifiers.putAll(filter(objectMapper.readValue(resource.getInputStream(), mapType)));
        }
    }
    else
    {
        LOGGER.warn("Known issue functionality is not available. No resource is found by location pattern: {}",
                locationPattern);
    }
}
 
源代码2 项目: openapi-generator   文件: ZebraTest.java
/**
 * Test the property 'type'
 */
@Test
public void typeTest() {
    String zebraJson = "{\"type\":\"mountain\",\"className\":\"zebra\",\"key1\":\"value1\",\"key2\":12321}";

    JSON j = new JSON();
    TypeFactory typeFactory = j.getMapper().getTypeFactory();
    MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, Object.class);
    try {
        HashMap<String, Object> map = j.getMapper().readValue(zebraJson, mapType);
        Assert.assertEquals(map.get("type"), "mountain");

        Map<String,Object> result =
                j.getMapper().readValue(zebraJson, new TypeReference<Map<String,Object>>() {});

        Assert.assertEquals(result.get("type"), "mountain");
    } catch (Exception ex) {
        Assert.assertEquals(true, false); // exception shouldn't be thrown
    }

}
 
Object deserialize(JsonNode node, String fieldName, Class targetClass, DeserializationContext ctxt) throws IOException {
    final String type = getFieldClassFQN(targetClass, valueType);
    try {
        // load class of the field
        final Class<?> fieldClass = Thread.currentThread().getContextClassLoader().loadClass(type);
        // create a map type matching the type of the field from the mapping information
        final YAMLMapper codec = (YAMLMapper) ctxt.getParser().getCodec();
        MapType mapType = codec.getTypeFactory().constructMapType(Map.class, String.class, fieldClass);
        // get a parser taking the current value as root
        final JsonParser traverse = node.get(fieldName).traverse(codec);
        // and use it to deserialize the subtree as the map type we just created
        return codec.readValue(traverse, mapType);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Unsupported type '" + type + "' for field '" + fieldName +
                "' on '" + targetClass.getName() + "' class. Full type was " + this, e);
    }
}
 
源代码4 项目: caravan   文件: CustomMessageElementVisitor.java
protected FieldElement buildFieldElement(BeanProperty writer, Label label) throws JsonMappingException {
  FieldElement.Builder fBuilder = FieldElement.builder();

  fBuilder.name(writer.getName());
  fBuilder.tag(nextTag(writer));

  JavaType type = writer.getType();

  if (type.isArrayType() && type.getContentType().getRawClass() == byte.class) {
    fBuilder.label(label);
    fBuilder.type(ScalarType.BYTES);
  } else if (type.isArrayType() || type.isCollectionLikeType()) {
    fBuilder.label(Label.REPEATED);
    fBuilder.type(getDataType(type.getContentType()));
  } else if (type instanceof MapType) {
    Class<?> wrapperClass = DynamicClassFactory.INSTANCE.fetchOrCreatePairClass((MapType) type);

    fBuilder.label(Label.REPEATED);
    fBuilder.type(getDataType(SimpleType.constructUnsafe(wrapperClass)));
  } else {
    fBuilder.label(label);
    fBuilder.type(getDataType(type));
  }
  return fBuilder.build();
}
 
源代码5 项目: auth0-java   文件: ExtendedBaseRequest.java
/**
 * Responsible for parsing an unsuccessful request (status code other than 200)
 * and generating a developer-friendly exception with the error details.
 *
 * @param response the unsuccessful response, as received. If its body is accessed, the buffer must be closed.
 * @return the exception with the error details.
 */
protected Auth0Exception createResponseException(Response response) {
    if (response.code() == STATUS_CODE_TOO_MANY_REQUEST) {
        return createRateLimitException(response);
    }

    String payload = null;
    try (ResponseBody body = response.body()) {
        payload = body.string();
        MapType mapType = mapper.getTypeFactory().constructMapType(HashMap.class, String.class, Object.class);
        Map<String, Object> values = mapper.readValue(payload, mapType);
        return new APIException(values, response.code());
    } catch (IOException e) {
        return new APIException(payload, response.code(), e);
    }
}
 
@Override
public JsonDeserializer<?> findMapDeserializer(MapType type,
        DeserializationConfig config, BeanDescription beanDesc,
        KeyDeserializer keyDeserializer,
        TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer)
    throws JsonMappingException
{
    Class<?> raw = type.getRawClass();

    if (PMap.class.isAssignableFrom(raw)) {
        if (raw.isAssignableFrom(HashPMap.class)) {
            return new HashTreePMapDeserializer(type, keyDeserializer, elementTypeDeserializer, elementDeserializer);
        }
    }

    return null;
}
 
源代码7 项目: logsniffer   文件: CoreAppConfig.java
@Bean
public ObjectMapper jsonObjectMapper() {
	final ObjectMapper jsonMapper = new ObjectMapper();
	jsonMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
	jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	jsonMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
	jsonMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
	jsonMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);

	final SimpleModule module = new SimpleModule("FieldsMapping", Version.unknownVersion());
	module.setSerializerModifier(new BeanSerializerModifier() {
		@Override
		public JsonSerializer<?> modifyMapSerializer(final SerializationConfig config, final MapType valueType,
				final BeanDescription beanDesc, final JsonSerializer<?> serializer) {
			if (FieldsMap.class.isAssignableFrom(valueType.getRawClass())) {
				return new FieldsMapMixInLikeSerializer();
			} else {
				return super.modifyMapSerializer(config, valueType, beanDesc, serializer);
			}
		}
	});
	jsonMapper.registerModule(module);
	return jsonMapper;
}
 
源代码8 项目: proarc   文件: JsonValueMap.java
public static JsonValueMap fromBundle(BundleName bundle, Locale locale) {
    JsonValueMap jvm = new JsonValueMap();
    jvm.setMapId(bundle.getValueMapId());

    URL resource = findResource(bundle.toString(), CONTROL, locale);
    if (resource == null) {
        return jvm;
    }
    ObjectMapper om = JsonUtils.defaultObjectMapper();
    try {
        TypeFactory typeFactory = om.getTypeFactory();
        MapType jsonType = typeFactory.constructMapType(Map.class, String.class, Object.class);
        Map<String, Object> jsonMap = om.readValue(resource, jsonType);
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine(String.valueOf(jsonMap));
        }
        Object data = jsonMap.get("data");
        jvm.setValues((List<Map<String, Object>>) data);
    } catch (Exception ex) {
        LOG.log(Level.WARNING, "Cannot read resource " + resource, ex);
    }
    return jvm;
}
 
源代码9 项目: cyclops   文件: PersistentMapSerializer.java
@Override
public void serialize(PersistentMap<?, ?> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {

  if(value.iterator().hasNext()) {
    Tuple2<?,?> keyAndValue = value.iterator().next();
    MapType type = TypeFactory.defaultInstance().constructMapType(Map.class, keyAndValue._1().getClass(),
      keyAndValue._2().getClass());
    serializers.findTypedValueSerializer(type,true,null)
      .serialize(value.mapView(),gen,serializers);
  }
  else{
    serializers.findValueSerializer(Map.class)
      .serialize(new HashMap<>(),gen,serializers);
  }


}
 
源代码10 项目: helios   文件: PersistentPathChildrenCache.java
public PersistentPathChildrenCache(final CuratorFramework curator, final String path,
                                   final String clusterId, final Path snapshotFile,
                                   final JavaType valueType)
    throws IOException, InterruptedException {
  this.curator = curator;
  this.path = path;
  this.clusterId = clusterId;
  this.valueType = valueType;

  final MapType mapType = Json.typeFactory().constructMapType(HashMap.class,
      Json.type(String.class), valueType);
  final Supplier<Map<String, T>> empty = Suppliers.ofInstance(Collections.<String, T>emptyMap());

  this.snapshot = PersistentAtomicReference.create(snapshotFile, mapType, empty);
  this.reactor = new DefaultReactor("zk-ppcc:" + path, new Update(), REFRESH_INTERVAL_MILLIS);
  curator.getConnectionStateListenable().addListener(new ConnectionListener());
}
 
源代码11 项目: camunda-bpm-elasticsearch   文件: JsonHelper.java
public static Map<String, Object> readJsonFromClasspathAsMap(String fileName) {
  InputStream inputStream = null;

  try {
    inputStream = IoUtil.getResourceAsStream(fileName);
    if (inputStream == null) {
      throw new RuntimeException("File '" + fileName + "' not found!");
    }

    MapType type = TypeFactory.defaultInstance().constructMapType(HashMap.class, String.class, Object.class);
    HashMap<String, Object> mapping = objectMapper.readValue(inputStream, type);

    return mapping;
  } catch (IOException e) {
    throw new RuntimeException("Unable to load json [" + fileName + "] from classpath", e);
  } finally {
    IoUtil.closeSilently(inputStream);
  }
}
 
源代码12 项目: fastjgame   文件: JsonUtils.java
/**
 * 解析json字符串为map对象。
 */
public static <M extends Map> M readMapFromJson(@Nonnull String json,
                                                @Nonnull Class<M> mapClass,
                                                @Nonnull Class<?> keyClass,
                                                @Nonnull Class<?> valueClass) {
    ObjectMapper mapper = getMapper();
    MapType mapType = mapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
    try {
        return mapper.readValue(json, mapType);
    } catch (IOException e) {
        return ExceptionUtils.rethrow(e);
    }
}
 
源代码13 项目: fastjgame   文件: JsonUtils.java
/**
 * 解析json字符串的字节数组为map对象。
 */
public static <M extends Map<?, ?>> M readMapFromJsonBytes(@Nonnull byte[] jsonBytes,
                                                           @Nonnull Class<M> mapClass,
                                                           @Nonnull Class<?> keyClass,
                                                           @Nonnull Class<?> valueClass) {
    ObjectMapper mapper = getMapper();
    MapType mapType = mapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
    try {
        return mapper.readValue(jsonBytes, mapType);
    } catch (IOException e) {
        return ExceptionUtils.rethrow(e);
    }
}
 
源代码14 项目: SpringBoot2.0   文件: JSONUtil.java
public static <K, V> Map<K, V> toMap(String json) {
    MapType mapType = mapper.getTypeFactory().constructRawMapType(Map.class);
    try {
        return mapper.readValue(json, mapType);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException();
    }
}
 
源代码15 项目: lams   文件: SimpleSerializers.java
@Override
public JsonSerializer<?> findMapSerializer(SerializationConfig config,
        MapType type, BeanDescription beanDesc,
        JsonSerializer<Object> keySerializer,
        TypeSerializer elementTypeSerializer, JsonSerializer<Object> elementValueSerializer) {
    return findSerializer(config, type, beanDesc);
}
 
@Override
public JsonDeserializer<?> findMapDeserializer(MapType type, DeserializationConfig config, BeanDescription beanDesc,
                                               KeyDeserializer keyDeserializer, TypeDeserializer elementTypeDeserializer,
                                               JsonDeserializer<?> elementDeserializer) throws JsonMappingException {
    for (Deserializers deserializers : deserializersList) {
        JsonDeserializer<?> deserializer = deserializers.findMapDeserializer(type, config, beanDesc, keyDeserializer, elementTypeDeserializer, elementDeserializer);
        if (deserializer != null) {
            return deserializer;
        }
    }
    return null;
}
 
源代码17 项目: keycloak-config-cli   文件: CloneUtil.java
private static Map<String, Object> jsonNodeToMap(JsonNode objectAsNode) {
    MapType typeRef = nonFailingMapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class);
    Map<String, Object> objectAsMap;

    try {
        ObjectReader reader = nonFailingMapper.readerFor(typeRef);
        objectAsMap = reader.readValue(objectAsNode);
    } catch (IOException e) {
        throw new ImportProcessingException(e);
    }

    return objectAsMap;
}
 
源代码18 项目: auth0-java   文件: MockServer.java
public static Map<String, Object> bodyFromRequest(RecordedRequest request) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    MapType mapType = mapper.getTypeFactory().constructMapType(HashMap.class, String.class, Object.class);
    try (Buffer body = request.getBody()) {
        return mapper.readValue(body.inputStream(), mapType);
    }
}
 
源代码19 项目: conductor   文件: ElasticSearchDAOV5.java
private List<Message> mapGetMessagesResponse(SearchResponse response) throws IOException {
    SearchHit[] hits = response.getHits().getHits();
    TypeFactory factory = TypeFactory.defaultInstance();
    MapType type = factory.constructMapType(HashMap.class, String.class, String.class);
    List<Message> messages = new ArrayList<>(hits.length);
    for (SearchHit hit : hits) {
        String source = hit.getSourceAsString();
        Map<String, String> mapSource = objectMapper.readValue(source, type);
        Message msg = new Message(mapSource.get("messageId"), mapSource.get("payload"), null);
        messages.add(msg);
    }
    return messages;
}
 
源代码20 项目: conductor   文件: ElasticSearchRestDAOV5.java
private List<Message> mapGetMessagesResponse(SearchResponse response) throws IOException {
    SearchHit[] hits = response.getHits().getHits();
    TypeFactory factory = TypeFactory.defaultInstance();
    MapType type = factory.constructMapType(HashMap.class, String.class, String.class);
    List<Message> messages = new ArrayList<>(hits.length);
    for (SearchHit hit : hits) {
        String source = hit.getSourceAsString();
        Map<String, String> mapSource = objectMapper.readValue(source, type);
        Message msg = new Message(mapSource.get("messageId"), mapSource.get("payload"), null);
        messages.add(msg);
    }
    return messages;
}
 
源代码21 项目: conductor   文件: ElasticSearchRestDAOV6.java
private List<Message> mapGetMessagesResponse(SearchResponse response) throws IOException {
    SearchHit[] hits = response.getHits().getHits();
    TypeFactory factory = TypeFactory.defaultInstance();
    MapType type = factory.constructMapType(HashMap.class, String.class, String.class);
    List<Message> messages = new ArrayList<>(hits.length);
    for (SearchHit hit : hits) {
        String source = hit.getSourceAsString();
        Map<String, String> mapSource = objectMapper.readValue(source, type);
        Message msg = new Message(mapSource.get("messageId"), mapSource.get("payload"), null);
        messages.add(msg);
    }
    return messages;
}
 
源代码22 项目: conductor   文件: ElasticSearchDAOV6.java
private List<Message> mapGetMessagesResponse(SearchResponse response) throws IOException {
    SearchHit[] hits = response.getHits().getHits();
    TypeFactory factory = TypeFactory.defaultInstance();
    MapType type = factory.constructMapType(HashMap.class, String.class, String.class);
    List<Message> messages = new ArrayList<>(hits.length);
    for (SearchHit hit : hits) {
        String source = hit.getSourceAsString();
        Map<String, String> mapSource = objectMapper.readValue(source, type);
        Message msg = new Message(mapSource.get("messageId"), mapSource.get("payload"), null);
        messages.add(msg);
    }
    return messages;
}
 
@SuppressWarnings( "unchecked" )
protected TableSerializer(final TableSerializer src,
        final BeanProperty property,
        final TypeFactory typeFactory,
        final JsonSerializer<?> rowKeySerializer,
        final JsonSerializer<?> columnKeySerializer,
        final TypeSerializer valueTypeSerializer,
        final JsonSerializer<?> valueSerializer)
{
    super(src, property);
    _type = src._type;
    _rowSerializer = (JsonSerializer<Object>) rowKeySerializer;
    _columnSerializer = (JsonSerializer<Object>) columnKeySerializer;
    _valueTypeSerializer = valueTypeSerializer;
    _valueSerializer = (JsonSerializer<Object>) valueSerializer;
    
    final MapType columnAndValueType = typeFactory.constructMapType(Map.class,
            _type.containedTypeOrUnknown(1), _type.containedTypeOrUnknown(2));

    JsonSerializer<?> columnAndValueSerializer = 
            MapSerializer.construct((Set<String>) null,
                                    columnAndValueType,
                                    false,
                                    _valueTypeSerializer,
                                    _columnSerializer,
                                    _valueSerializer,
                                    null);

    final MapType rowMapType = typeFactory.constructMapType(Map.class,
            _type.containedTypeOrUnknown(0), columnAndValueType);
    _rowMapSerializer =
            MapSerializer.construct((Set<String>) null,
                                    rowMapType,
                                    false,
                                    null,
                                    _rowSerializer,
                                    (JsonSerializer<Object>) columnAndValueSerializer,
                                    null);
}
 
protected PCollectionsMapDeserializer(MapType type, KeyDeserializer keyDeser,
        TypeDeserializer typeDeser, JsonDeserializer<?> deser)
{
    super(type);
    _mapType = type;
    _keyDeserializer = keyDeser;
    _typeDeserializerForValue = typeDeser;
    _valueDeserializer = deser;
}
 
源代码25 项目: graphql-spqr   文件: ConvertingDeserializers.java
@Override
public JsonDeserializer<?> findMapDeserializer(MapType type, DeserializationConfig config,
                                               BeanDescription beanDesc, KeyDeserializer keyDeserializer,
                                               TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer) {

    return forJavaType(type);
}
 
源代码26 项目: endpoints-java   文件: ObjectMapperUtil.java
@Override
public JsonSerializer<?> modifyMapSerializer(SerializationConfig config, MapType valueType,
    BeanDescription beanDesc, JsonSerializer<?> serializer) {
  if (serializer instanceof MapSerializer) {
    // TODO: We should probably be propagating the NON_EMPTY inclusion here, but it's breaking
    // discovery.
    return new DeepEmptyCheckingSerializer<>(serializer);
  }
  return serializer;
}
 
源代码27 项目: emodb   文件: LazyJsonModule.java
@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;
        }
    });
}
 
源代码28 项目: archie   文件: ADLListener.java
public void enterComponent_terminologies_section(AdlParser.Component_terminologies_sectionContext ctx) {
    if(archetype instanceof OperationalTemplate) {
        OperationalTemplate template = (OperationalTemplate) archetype;

        TypeFactory typeFactory = OdinToJsonConverter.getObjectMapper().getTypeFactory();
        MapType mapType = typeFactory.constructMapType(ConcurrentHashMap.class, String.class, ArchetypeTerminology.class);

        template.setComponentTerminologies(OdinObjectParser.convert(ctx.odin_text(), mapType));
    } else {
        throw new IllegalArgumentException("cannot add component terminologies to anything but an operational template");
    }
}
 
@Test
public void testSave() throws IOException, ConfigurationException
{
    // save the Configuration as a String...
    final StringWriter sw = new StringWriter();
    jsonConfiguration.write(sw);
    final String output = sw.toString();

    // ..and then try parsing it back
    final ObjectMapper mapper = new ObjectMapper();
    final MapType type = mapper.getTypeFactory().constructMapType(Map.class,
            String.class, Object.class);
    final Map<String, Object> parsed = mapper.readValue(output, type);
    assertEquals(7, parsed.entrySet().size());
    assertEquals("value1", parsed.get("key1"));

    final Map key2 = (Map) parsed.get("key2");
    assertEquals("value23", key2.get("key3"));

    final List<String> key5 =
            (List<String>) ((Map) parsed.get("key4")).get("key5");
    assertEquals(2, key5.size());
    assertEquals("col1", key5.get(0));
    assertEquals("col2", key5.get(1));

    final List<?> capitals = (List<?>) parsed.get("capitals");
    final Map<?, ?> capUk = (Map<?, ?>) capitals.get(1);
    assertEquals("London", capUk.get("capital"));
}
 
源代码30 项目: lams   文件: BeanDeserializerModifier.java
/**
 * @since 2.2
 */
public JsonDeserializer<?> modifyMapDeserializer(DeserializationConfig config,
        MapType type, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
    return deserializer;
}
 
如果文章对您有帮助,请点击页面广告。以鼓励作者做出的努力。
 同包方法