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

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#treeToValue() . 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: Deserializer.java    From nodes with Apache License 2.0 6 votes vote down vote up
@Override
public Resource<T> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {

    Resource<T> resourceModel = new Resource<T>();

    ObjectMapper mapper = objectMapperFactory.newDeserializerMapper();
    ObjectCodec oc = jsonParser.getCodec();
    JsonNode node = oc.readTree(jsonParser);

    T resource;

    GraphQLProperty graphQLProperty = t.getAnnotation(GraphQLProperty.class);
    if (graphQLProperty != null) {
        String resourceName = graphQLProperty.name();
        JsonNode innerNode = node.get(resourceName);
        resource = mapper.treeToValue(innerNode, t);
    } else {
        resource = mapper.readValue(node.toString(), t);
    }

    resourceModel.setResource(resource);

    return resourceModel;
}
 
Example 2
Source File: IdAnnotationModuleTest.java    From immutables with Apache License 2.0 6 votes vote down vote up
/**
 * Check annotation lookup for java beans
 */
@ParameterizedTest
@MethodSource("mappers")
void javaBean(ObjectMapper mapper) throws IOException {
  JavaBean1 bean1 = new JavaBean1();
  bean1.setString1("id123");
  bean1.setInt1(42);
  bean1.setBase("base1");

  ObjectNode node = mapper.valueToTree(bean1);
  check(ImmutableList.copyOf(node.fieldNames())).has("_id");
  check(node.get("_id").asText()).is("id123");
  check(ImmutableList.copyOf(node.fieldNames())).not().has("string1");

  JavaBean1 bean2 = mapper.treeToValue(node, JavaBean1.class);
  check(bean2.getString1()).is("id123");
  check(bean2.getInt1()).is(42);
  check(bean2.getBase()).is("base1");
}
 
Example 3
Source File: MultipleClassesDeserializer.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Object readValue(ObjectMapper mapper, JsonNode root, Class<?> clazz) {
    try {
        return mapper.treeToValue(root, clazz);
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: HistoryTrendPlugin.java    From allure2 with Apache License 2.0 5 votes vote down vote up
@Override
protected Optional<HistoryTrendItem> parseItem(final ObjectMapper mapper, final JsonNode child)
        throws JsonProcessingException {

    if (Objects.nonNull(child.get("total"))) {
        final Statistic statistic = mapper.treeToValue(child, Statistic.class);
        return Optional.of(new HistoryTrendItem().setStatistic(statistic));
    }
    return Optional.ofNullable(mapper.treeToValue(child, HistoryTrendItem.class));
}
 
Example 5
Source File: FailOnNumbersForEnumsTest.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@Test
public void testDisabled() throws JsonProcessingException {
  ObjectMapper mapper = objectMapper(false);

  AllFields parsed = mapper.treeToValue(buildNode(), AllFields.class);
  assertThat(parsed.hasEnum()).isTrue();
  assertThat(parsed.getEnum()).isEqualTo(TestProtobuf.Enum.TWO);
}
 
Example 6
Source File: ObjectMapperHelper.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T extends MessageOrBuilder> T writeAndReadBack(ObjectMapper mapper, T value) {
  TreeNode tree = toTree(mapper, value);

  try {
    return (T) mapper.treeToValue(tree, value.getClass());
  } catch (JsonProcessingException e) {
    throw new RuntimeException(e);
  }
}
 
Example 7
Source File: OperatorDeserializer.java    From yare with MIT License 5 votes vote down vote up
private List<Operand> mapNodeAsListOfOperands(JsonNode jsonNode, ObjectMapper objectMapper) throws JsonProcessingException {
    Iterator<JsonNode> operandNodes = jsonNode.iterator();
    List<Operand> operands = new ArrayList<>();
    while (operandNodes.hasNext()) {
        JsonNode node = operandNodes.next();
        Operand o = objectMapper.treeToValue(node, Operand.class);
        operands.add(o);
    }
    return operands;
}
 
Example 8
Source File: CentralRepoModule.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private static void populateFromAdminDefault(File file, ConfigRepositoryImpl configRepository)
        throws Exception {
    ObjectMapper mapper = ObjectMappers.create();
    String content = Files.asCharSource(file, UTF_8).read();
    JsonNode rootNode = mapper.readTree(content);
    AllAdminConfigUtil.updatePasswords(rootNode, configRepository);
    AllCentralAdminConfig config =
            mapper.treeToValue(rootNode, ImmutableAllCentralAdminConfig.class);
    configRepository.updateAllCentralAdminConfig(config, null);
}
 
Example 9
Source File: JacksonUtil.java    From litemall with MIT License 5 votes vote down vote up
public static <T> T parseObject(String body, String field, Class<T> clazz) {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node;
    try {
        node = mapper.readTree(body);
        node = node.get(field);
        return mapper.treeToValue(node, clazz);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}
 
Example 10
Source File: ExtensionDeserializer.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public Extension deserialize(JsonParser jp,
                             DeserializationContext ctxt) throws IOException {

    ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    JsonNode node = jp.getCodec().readTree(jp);

    String extensionId = node.get("extensionid").asText();

    if (context != null) {
        try {
            String result = context.getPropertySource().getProperty(extensionId);

            if (result != null) {
                extensionId = result;
            }
        } catch (Exception e) {
            logger.info("Exception trying to evaluate property: {}", e.getMessage());
        }
    }

    // based on the name return the specific extension impl
    if (extensionsMap != null && extensionsMap.containsKey(extensionId)) {
        return mapper.treeToValue(node,
                                  extensionsMap.get(extensionId));
    } else {
        throw new IllegalArgumentException("Extension handler not registered for: " + extensionId);
    }
}
 
Example 11
Source File: JacksonUtil.java    From BigDataPlatform with GNU General Public License v3.0 5 votes vote down vote up
public static <T> T parseObject(String body, String field, Class<T> clazz) {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node;
    try {
        node = mapper.readTree(body);
        node = node.get(field);
        return mapper.treeToValue(node, clazz);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}
 
Example 12
Source File: ReadUnknownEnumValuesAsNullTest.java    From jackson-datatype-protobuf with Apache License 2.0 4 votes vote down vote up
@Test(expected = JsonMappingException.class)
public void testIntDisabled() throws JsonProcessingException {
  ObjectMapper mapper = objectMapper(false);

  mapper.treeToValue(buildNode(999999), AllFields.class);
}
 
Example 13
Source File: ValueDeserializer.java    From yare with MIT License 4 votes vote down vote up
private Object mapValueByType(JsonNode jsonNode, String type, ObjectMapper objectMapper) throws JsonProcessingException {
    Class<?> resolvedType = (Class<?>) typeConverter.fromString(Type.class, type);
    return objectMapper.treeToValue(jsonNode, resolvedType);
}
 
Example 14
Source File: ReadUnknownEnumValuesAsNullTest.java    From jackson-datatype-protobuf with Apache License 2.0 4 votes vote down vote up
@Test(expected = JsonMappingException.class)
public void testStringDisabled() throws JsonProcessingException {
  ObjectMapper mapper = objectMapper(false);

  mapper.treeToValue(buildNode("fakeValue"), AllFields.class);
}
 
Example 15
Source File: AttributeDeserializer.java    From yare with MIT License 4 votes vote down vote up
private Object mapValueByType(JsonNode jsonNode, String type, ObjectMapper objectMapper) throws JsonProcessingException {
    Class<?> resolvedType = (Class<?>) typeConverter.fromString(Type.class, type);
    return objectMapper.treeToValue(jsonNode, resolvedType);
}
 
Example 16
Source File: ParameterDeserializer.java    From yare with MIT License 4 votes vote down vote up
private Expression getExpression(JsonNode jsonNode, ObjectMapper objectMapper) throws JsonProcessingException {
    return jsonNode != null ? objectMapper.treeToValue(jsonNode, Expression.class) : null;
}
 
Example 17
Source File: StatisticsService.java    From jhipster-online with Apache License 2.0 4 votes vote down vote up
@Transactional
@Async("statisticsExecutor")
public void addEntry(String entry, String host) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNodeRoot = mapper.readTree(entry);
    JsonNode jsonNodeGeneratorJHipster = jsonNodeRoot.get("generator-jhipster");
    String generatorGuid = jsonNodeRoot.get("generator-id").asText();
    String generatorVersion = jsonNodeRoot.get("generator-version").asText();
    String gitProvider = jsonNodeRoot.get("git-provider").asText();
    String nodeVersion = jsonNodeRoot.get("node-version").asText();
    String os = jsonNodeRoot.get("os").asText();
    String arch = jsonNodeRoot.get("arch").asText();
    String cpu = jsonNodeRoot.get("cpu").asText();
    String cores = jsonNodeRoot.get("cores").asText();
    String memory = jsonNodeRoot.get("memory").asText();
    String userLanguage = jsonNodeRoot.get("user-language").asText();

    YoRC yorc = mapper.treeToValue(jsonNodeGeneratorJHipster, YoRC.class);

    Instant now = Instant.now();
    DateUtil.setAbsoluteDate(yorc, now);

    yorc.jhipsterVersion(generatorVersion)
        .gitProvider(gitProvider)
        .nodeVersion(nodeVersion)
        .os(os)
        .arch(arch)
        .cpu(cpu)
        .cores(cores)
        .memory(memory)
        .userLanguage(userLanguage)
        .creationDate(now);

    log.info("Adding an entry for generator {}.", generatorGuid);
    this.tryToCreateGeneratorIdentityAndIgnoreErrors(generatorGuid);

    Optional<GeneratorIdentity> generatorIdentity = generatorIdentityService.findOneByGuid(generatorGuid);

    if (generatorIdentity.isPresent()) {
        generatorIdentity.get().host(host);
        yorc.owner(generatorIdentity.get());
    } else {
        log.info("GeneratorIdentity {} was not correctly created", generatorGuid);
    }

    yoRCService.save(yorc);
}
 
Example 18
Source File: GenericResultSetMapper.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
private <E extends AbstractEntity> List<E> toEntityList(ResultSet rs,
    Class<E> entityClass) throws Exception {
  String tableName =
      entityMappingHolder.tableToEntityNameMap.inverse().get(entityClass.getSimpleName());
  LinkedHashMap<String, ColumnInfo> columnInfoMap =
      entityMappingHolder.columnInfoPerTable.get(tableName);
  List<E> entityList = new ArrayList<>();

  ObjectMapper mapper = new ObjectMapper();
  while (rs.next()) {
    AbstractEntity entityObj = entityClass.newInstance();
    ResultSetMetaData resultSetMetaData = rs.getMetaData();
    int numColumns = resultSetMetaData.getColumnCount();
    ObjectNode objectNode = mapper.createObjectNode();
    for (int i = 1; i <= numColumns; i++) {
      String dbColumnName = resultSetMetaData.getColumnLabel(i).toLowerCase();
      ColumnInfo columnInfo = columnInfoMap.get(dbColumnName);
      Field field = columnInfo.field;
      Object val;
      if (columnInfo.sqlType == Types.CLOB) {
        Clob clob = rs.getClob(i);
        val = clob.getSubString(1, (int) clob.length());
      } else {
        val = rs.getObject(i);
      }
      if (val == null) {
        continue;
      }
      if (field.getType().isAssignableFrom(Timestamp.class)) {
        objectNode.put(field.getName(), ((Timestamp) val).getTime());
      } else {
        objectNode.put(field.getName(), val.toString());
      }

      /*
       * if (Enum.class.isAssignableFrom(field.getType())) { field.set(entityObj,
       * Enum.valueOf(field.getType().asSubclass(Enum.class), val.toString())); } else if
       * (String.class.isAssignableFrom(field.getType())) { field.set(entityObj, val.toString());
       * } else if (Integer.class.isAssignableFrom(field.getType())) { field.set(entityObj,
       * Integer.valueOf(val.toString())); } else if
       * (Long.class.isAssignableFrom(field.getType())) { field.set(entityObj,
       * Long.valueOf(val.toString())); } else { field.set(entityObj, val); }
       */
    }
    entityObj = mapper.treeToValue(objectNode, entityClass);
    entityList.add((E) entityObj);
  }

  return entityList;

}
 
Example 19
Source File: BitbucketManager.java    From scava with Eclipse Public License 2.0 3 votes vote down vote up
@Override
public Date getFirstDate(DB db, BitbucketBugTrackingSystem bitbucketTracker) throws Exception {
	
	setClient(bitbucketTracker);
	
	Date firstDate = null;
	
	ObjectMapper mapper = new ObjectMapper();
	
	mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

	ProcessedBitBucketURL processedURL= new ProcessedBitBucketURL(bitbucketTracker);
	
	HttpUrl.Builder builder = HttpUrl.parse(processedURL.getHost() + exthost).newBuilder();
	builder.addEncodedPathSegment(processedURL.getOwner());
	builder.addEncodedPathSegment(processedURL.getRepository());
	builder.addEncodedPathSegment("issues");
	builder.addEncodedQueryParameter("sort", "created_on");
	builder.addEncodedQueryParameter("pagelen", PAGE_SIZE); // page size

	this.builder = builder.toString();

	Request request = new Request.Builder().url(builder.toString()).get().build();

	Response response = this.client.newCall(request).execute();

	JsonNode rootNode = new ObjectMapper().readTree(response.body().string());

	if (rootNode.get("values").isArray()) {
		Issue issue = mapper.treeToValue(rootNode.get("values").get(0), Issue.class);
		firstDate = new Date(convertStringToDate(issue.getCreatedOn()).toString());
	}

	// No need for pagination - issues are returned as an array.

	response.close();

	return firstDate;

}
 
Example 20
Source File: AbstractRestIntegrationTest.java    From registry with Apache License 2.0 2 votes vote down vote up
/**
 * Get response code from the response string.
 *
 * @param response
 * @return
 * @throws Exception
 */
public int getResponseCode(String response) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper.readTree(response);
    return mapper.treeToValue(node.get("responseCode"), Integer.class);
}