com.fasterxml.jackson.databind.type.MapType Java Examples

The following examples show how to use com.fasterxml.jackson.databind.type.MapType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KnownIssueProvider.java    From vividus with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #2
Source File: PCollectionsDeserializers.java    From jackson-datatypes-collections with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #3
Source File: ExtendedBaseRequest.java    From auth0-java with MIT License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #4
Source File: CoreAppConfig.java    From logsniffer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #5
Source File: CustomMessageElementVisitor.java    From caravan with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #6
Source File: JsonValueMap.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #7
Source File: PersistentMapSerializer.java    From cyclops with Apache License 2.0 6 votes vote down vote up
@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);
  }


}
 
Example #8
Source File: ClassWithInterfaceFieldsRegistry.java    From istio-java-api with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #9
Source File: ZebraTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * 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
    }

}
 
Example #10
Source File: PersistentPathChildrenCache.java    From helios with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #11
Source File: JsonHelper.java    From camunda-bpm-elasticsearch with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example #12
Source File: ADLListener.java    From archie with Apache License 2.0 5 votes vote down vote up
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");
    }
}
 
Example #13
Source File: TestJSONConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example #14
Source File: LazyJsonModule.java    From emodb with Apache License 2.0 5 votes vote down vote up
@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;
        }
    });
}
 
Example #15
Source File: ObjectMapperUtil.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #16
Source File: ConvertingDeserializers.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public JsonDeserializer<?> findMapDeserializer(MapType type, DeserializationConfig config,
                                               BeanDescription beanDesc, KeyDeserializer keyDeserializer,
                                               TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer) {

    return forJavaType(type);
}
 
Example #17
Source File: PCollectionsMapDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
protected PCollectionsMapDeserializer(MapType type, KeyDeserializer keyDeser,
        TypeDeserializer typeDeser, JsonDeserializer<?> deser)
{
    super(type);
    _mapType = type;
    _keyDeserializer = keyDeser;
    _typeDeserializerForValue = typeDeser;
    _valueDeserializer = deser;
}
 
Example #18
Source File: ElasticSearchDAOV6.java    From conductor with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #19
Source File: TableSerializer.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #20
Source File: ElasticSearchRestDAOV6.java    From conductor with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #21
Source File: ElasticSearchRestDAOV5.java    From conductor with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #22
Source File: JsonUtils.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
/**
 * 解析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);
    }
}
 
Example #23
Source File: ElasticSearchDAOV5.java    From conductor with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #24
Source File: MockServer.java    From auth0-java with MIT License 5 votes vote down vote up
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);
    }
}
 
Example #25
Source File: CloneUtil.java    From keycloak-config-cli with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #26
Source File: CompositeDeserializers.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #27
Source File: JsonUtils.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
/**
 * 解析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);
    }
}
 
Example #28
Source File: JSONUtil.java    From SpringBoot2.0 with Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example #29
Source File: SimpleSerializers.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JsonSerializer<?> findMapSerializer(SerializationConfig config,
        MapType type, BeanDescription beanDesc,
        JsonSerializer<Object> keySerializer,
        TypeSerializer elementTypeSerializer, JsonSerializer<Object> elementValueSerializer) {
    return findSerializer(config, type, beanDesc);
}
 
Example #30
Source File: JsonTransformer.java    From camunda-bpm-elasticsearch with Apache License 2.0 4 votes vote down vote up
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);
}