Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#getTypeFactory()

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#getTypeFactory() . 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: 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 2
Source File: StringArrayColumnAdapter.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public List<String> fromCursor(Cursor cursor, String columnName) {
    int columnIndex = cursor.getColumnIndex(columnName);
    String sourceValue = cursor.getString(columnIndex);

    if (sourceValue == null || sourceValue.equals("")) {
        return Collections.emptyList();
    } else if (sourceValue.charAt(0) == '/') {
        return Arrays.asList(sourceValue.substring(1).split("/"));
    } else {
        ObjectMapper objectMapper  = new ObjectMapper();
        TypeFactory typeFactory = objectMapper.getTypeFactory();
        try {
            return objectMapper.readValue(sourceValue, typeFactory.constructCollectionType(List.class,
                    String.class));
        } catch (IOException e) {
            throw new RuntimeException("Couldn't deserialize string array");
        }
    }
}
 
Example 3
Source File: WithIdTest.java    From rest-schemagen with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDeserializeCorrectly() throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final TypeFactory typeFactory = mapper.getTypeFactory();

    UUID id = UUID.randomUUID();

    final String content = "{\"text\": \"foo\", \"number\": 123, \"id\": \"" + id.toString() + "\"}";

    final JavaType nameWithSchemaType = typeFactory.constructParametricType(WithId.class, Payload.class);
    final WithId<Payload> payloadWithId = mapper.readValue(content, nameWithSchemaType);

    assertThat(payloadWithId.object.text).isEqualTo("foo");
    assertThat(payloadWithId.object.number).isEqualTo(123);
    assertThat(payloadWithId.id).isEqualTo(id);
}
 
Example 4
Source File: TestDataProviderEngineTest.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteOnFile() throws IOException {
    TestDataProviderEngine engine = new TestDataProviderEngine();
    engine.setResourceLoader(new DefaultResourceLoader());
    engine.setPathOnDisk(testFolder.getRoot() + "/");

    N2oTestDataProvider provider = new N2oTestDataProvider();
    provider.setFile(testFile.getName());

    //Удаление данных
    provider.setOperation(delete);

    Map<String, Object> inParamsForDelete = new LinkedHashMap<>();
    inParamsForDelete.put("id", 1L);

    engine.invoke(provider, inParamsForDelete);

    //Проверка, что после delete, json файл содержит ожидаемые данные
    ObjectMapper objectMapper = new ObjectMapper();
    TypeFactory typeFactory = objectMapper.getTypeFactory();
    CollectionType collectionType = typeFactory.constructCollectionType(
            List.class, HashMap.class);
    List<Map> result = objectMapper.readValue(testFile, collectionType);

    assertThat(result.size(), is(0));
}
 
Example 5
Source File: WrappedListTest.java    From rest-schemagen with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDeserialize() throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final TypeFactory typeFactory = mapper.getTypeFactory();

    final String content = "{\"members\": [{\"value\": \"foo\", \"_schema\":{\"links\":[]}}, {\"value\": \"bar\", \"_schema\":{\"links\":[]}}]}";

    final TypeReference typeReference = new TypeReference<WrappedList<ObjectWithSchema<ListResponseTest.Payload>>>() {
    };
    final WrappedList<ObjectWithSchema<ListResponseTest.Payload>> listResponse = mapper.readValue(content, typeReference);

    assertThat(listResponse.members)
            .extracting(ObjectWithSchema::getObject)
            .extracting(p -> p.value)
            .containsExactly("foo", "bar");
}
 
Example 6
Source File: JsonHelper.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public static void writeRunningQueryList(Writer w,
		List<RunningQuery> rQueries) throws JsonGenerationException,
		JsonMappingException, IOException {
	final ObjectMapper mapper = new ObjectMapper();
	final TypeFactory typeFactory = mapper.getTypeFactory();
	final ObjectWriter writer = mapper.writerWithType(typeFactory
			.constructCollectionType(List.class,
					com.bigdata.rdf.sail.model.RunningQuery.class));

	writer.writeValue(w, rQueries);
}
 
Example 7
Source File: JsonUtils.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a configured mapper supporting JAXB.
 * @see #createObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)
 */
public static ObjectMapper createJaxbMapper() {
    ObjectMapper om = createObjectMapper(createObjectMapper());
    JaxbAnnotationIntrospector jaxbIntr = new JaxbAnnotationIntrospector(om.getTypeFactory());
    JacksonAnnotationIntrospector jsonIntr = new JacksonAnnotationIntrospector();
    om.setAnnotationIntrospector(new AnnotationIntrospectorPair(jsonIntr, jaxbIntr));
    return om;
}
 
Example 8
Source File: ObjectWithSchemaTest.java    From rest-schemagen with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDeserialize() throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final TypeFactory typeFactory = mapper.getTypeFactory();

    final String content = "{\"value\": \"foo\", \"_schema\": {\"links\": []}}";

    final JavaType nameWithSchemaType = typeFactory.constructParametricType(ObjectWithSchema.class, Payload.class);
    final ObjectWithSchema<Payload> objectWithSchema = mapper.readValue(content, nameWithSchemaType);

    assertThat(objectWithSchema.getObject().value).isEqualTo("foo");
    assertThat(objectWithSchema.getSchema().getLinks()).isEmpty();
    assertThat(objectWithSchema.getMessages()).isEmpty();
}
 
Example 9
Source File: PaginatedResponseTest.java    From rest-schemagen with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDeserialize() throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final TypeFactory typeFactory = mapper.getTypeFactory();

    final String content = "{\"members\": [{\"value\": \"foo\", \"_schema\":{\"links\": []}}, {\"value\": \"bar\", \"_schema\":{\"links\": []}}], \"offset\": 100, \"limit\": 10, \"total\": 2000, \"_schema\":{\"links\":[]}}";

    final JavaType nameWithSchemaType = typeFactory.constructParametricType(PaginatedResponse.class, Payload.class);
    final PaginatedResponse<Payload> listResponse = mapper.readValue(content, nameWithSchemaType);

    assertThat(listResponse.getMembers()).extracting(ObjectWithSchema::getObject).extracting(p -> p.value).containsExactly("foo", "bar");
    assertThat(listResponse.getLimit()).isEqualTo(10);
    assertThat(listResponse.getOffset()).isEqualTo(100);
    assertThat(listResponse.getTotal()).isEqualTo(2000);
}
 
Example 10
Source File: EventJson.java    From concursus with MIT License 5 votes vote down vote up
private BiFunction<JsonNode, Type, Object> makeDeserialiser(ObjectMapper mapper) {
    final TypeFactory typeFactory = mapper.getTypeFactory();
    return (node, type) -> {
        JavaType javaType = typeFactory.constructType(type);
        try {
            final JsonParser jsonParser = mapper.treeAsTokens(node);
            final ObjectCodec codec = jsonParser.getCodec();

            return codec.readValue(jsonParser, javaType);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    };
}
 
Example 11
Source File: CommandJson.java    From concursus with MIT License 5 votes vote down vote up
private BiFunction<JsonNode, Type, Object> makeDeserialiser(ObjectMapper mapper) {
    final TypeFactory typeFactory = mapper.getTypeFactory();
    return (node, type) -> {
        JavaType javaType = typeFactory.constructType(type);
        try {
            final JsonParser jsonParser = mapper.treeAsTokens(node);
            final ObjectCodec codec = jsonParser.getCodec();

            return codec.readValue(jsonParser, javaType);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    };
}
 
Example 12
Source File: Utility.java    From SNOMED-in-5-minutes with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the json for graph.
 *
 * @param object the object
 * @return the json for graph
 * @throws Exception the exception
 */
public static String getJsonForGraph(Object object) throws Exception {
  ObjectMapper mapper = new ObjectMapper();
  AnnotationIntrospector introspector =
      new JaxbAnnotationIntrospector(mapper.getTypeFactory());
  mapper.setAnnotationIntrospector(introspector);
  return mapper.writeValueAsString(object);
}
 
Example 13
Source File: ObjectMapperFactory.java    From data-highway with Apache License 2.0 5 votes vote down vote up
public static <T> ObjectMapper create(
    @NonNull Class<T> payloadClass,
    @NonNull PayloadTypeFactory payloadTypeFactory,
    JsonDeserializer<T> payloadDeserialiser) {
  ObjectMapper mapper = new ObjectMapper().disable(FAIL_ON_UNKNOWN_PROPERTIES);
  TypeFactory typeFactory = mapper.getTypeFactory();
  JavaType payloadType = payloadTypeFactory.construct(typeFactory);
  return mapper.registerModule(Event.module(typeFactory, payloadType, payloadClass, payloadDeserialiser));
}
 
Example 14
Source File: Utility.java    From SNOMED-in-5-minutes with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the graph for json.
 *
 * @param <T> the generic type
 * @param json the json
 * @param graphClass the graph class
 * @return the graph for json
 * @throws Exception the exception
 */
public static <T> T getGraphForJson(String json, Class<T> graphClass)
  throws Exception {
  InputStream in =
      new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
  ObjectMapper mapper = new ObjectMapper();
  AnnotationIntrospector introspector =
      new JaxbAnnotationIntrospector(mapper.getTypeFactory());
  mapper.setAnnotationIntrospector(introspector);
  return mapper.readValue(in, graphClass);

}
 
Example 15
Source File: MoreoverJsonActivitySerializer.java    From streams with Apache License 2.0 5 votes vote down vote up
@Override
public Activity deserialize(String serialized) {
  serialized = serialized.replaceAll("\\[[ ]*\\]", "null");

  LOGGER.debug(serialized);

  ObjectMapper mapper = new ObjectMapper();
  AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
  mapper.setAnnotationIntrospector(introspector);
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
  mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, Boolean.FALSE);
  mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE);
  mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE);
  mapper.configure(DeserializationFeature.WRAP_EXCEPTIONS, Boolean.TRUE);

  Article article;
  try {
    ObjectNode node = (ObjectNode)mapper.readTree(serialized);
    node.remove("tags");
    node.remove("locations");
    node.remove("companies");
    node.remove("topics");
    node.remove("media");
    node.remove("outboundUrls");
    ObjectNode jsonNodes = (ObjectNode) node.get("source").get("feed");
    jsonNodes.remove("editorialTopics");
    jsonNodes.remove("tags");
    jsonNodes.remove("autoTopics");
    article = mapper.convertValue(node, Article.class);
  } catch (IOException ex) {
    throw new IllegalArgumentException("Unable to deserialize", ex);
  }
  return MoreoverUtils.convert(article);
}
 
Example 16
Source File: AbstractTypeCustomizationFactory.java    From caravan with Apache License 2.0 5 votes vote down vote up
public AbstractTypeCustomizationFactory(ObjectMapper mapper) {
  this.serializerProvider = mapper.getSerializerProviderInstance();
  this.serializerFactory = (CustomBeanSerializerFactory) mapper.getSerializerFactory();
  this.typeFactory = mapper.getTypeFactory();

  this.deserializationContext = mapper.getDeserializationContext();
  this.deserializationConfig = mapper.getDeserializationConfig();
}
 
Example 17
Source File: TestDataProviderEngineTest.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateOnEmptyFile() throws IOException {
    TestDataProviderEngine engine = new TestDataProviderEngine();
    engine.setResourceLoader(new DefaultResourceLoader());
    engine.setPathOnDisk(testFolder.getRoot() + "/");

    N2oTestDataProvider provider = new N2oTestDataProvider();
    provider.setFile(emptyFile.getName());

    //Добавление новых данных в пустой файл
    provider.setOperation(create);

    Map<String, Object> inParamsForCreate = new LinkedHashMap<>();
    inParamsForCreate.put("name", "test10");
    inParamsForCreate.put("type", "10");

    engine.invoke(provider, inParamsForCreate);

    //Проверка, что после create, json файл содержит ожидаемые данные
    ObjectMapper objectMapper = new ObjectMapper();
    TypeFactory typeFactory = objectMapper.getTypeFactory();
    CollectionType collectionType = typeFactory.constructCollectionType(
            List.class, HashMap.class);
    List<Map> result = objectMapper.readValue(emptyFile, collectionType);

    assertThat(result.size(), is(1));
    assertThat(result.get(0).get("id"), is(1));
    assertThat(result.get(0).get("name"), is("test10"));
    assertThat(result.get(0).get("type"), is("10"));
}
 
Example 18
Source File: JsonHelper.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public static List<RunningQuery> readRunningQueryList(InputStream is)
		throws JsonProcessingException, IOException {

	final ObjectMapper mapper = new ObjectMapper();
	mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	final TypeFactory typeFactory = mapper.getTypeFactory();
	final ObjectReader reader = mapper.reader(typeFactory
			.constructCollectionType(List.class,
					com.bigdata.rdf.sail.model.RunningQuery.class));

	// TODO: Change this when upgrading to a newer Jackson version
	return (List<RunningQuery>) reader.readValue(is);

}
 
Example 19
Source File: TestDataProviderEngineTest.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateOnFile() throws IOException {
    TestDataProviderEngine engine = new TestDataProviderEngine();
    engine.setResourceLoader(new DefaultResourceLoader());
    engine.setPathOnDisk(testFolder.getRoot() + "/");

    N2oTestDataProvider provider = new N2oTestDataProvider();
    provider.setFile(testFile.getName());

    //Добавление новых данных
    provider.setOperation(create);

    Map<String, Object> inParamsForCreate = new LinkedHashMap<>();
    inParamsForCreate.put("id", 9L);
    inParamsForCreate.put("name", "test9");
    inParamsForCreate.put("type", "9");

    engine.invoke(provider, inParamsForCreate);

    //Проверка, что после create, json файл содержит ожидаемые данные
    ObjectMapper objectMapper = new ObjectMapper();
    TypeFactory typeFactory = objectMapper.getTypeFactory();
    CollectionType collectionType = typeFactory.constructCollectionType(
            List.class, HashMap.class);
    List<Map> result = objectMapper.readValue(testFile, collectionType);

    assertThat(result.size(), is(2));
    assertThat(result.get(0).get("id"), is(9));
    assertThat(result.get(0).get("name"), is("test9"));
    assertThat(result.get(0).get("type"), is("9"));
    assertThat(result.get(1).get("id"), is(1));
    assertThat(result.get(1).get("name"), is("test1"));
    assertThat(result.get(1).get("type"), is("1"));
}
 
Example 20
Source File: EventTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Test
public void message() throws Exception {
  ObjectMapper mapper = new ObjectMapper();
  TypeFactory typeFactory = mapper.getTypeFactory();
  mapper.registerModule(Event.module(typeFactory, typeFactory.constructType(Payload.class), Payload.class, null));
  Event event = new Message<>(0, 1L, 2, 3L, new Payload("bar"));
  String json = mapper.writeValueAsString(event);
  assertThat(json,
      is("{\"type\":\"MESSAGE\",\"partition\":0,\"offset\":1,\"schema\":2,\"timestampMs\":3,\"payload\":{\"foo\":\"bar\"}}"));
  Event result = mapper.readValue(json, Event.class);
  assertThat(result, is(event));
}