Example usage for com.fasterxml.jackson.databind ObjectMapper treeToValue

List of usage examples for com.fasterxml.jackson.databind ObjectMapper treeToValue

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper treeToValue.

Prototype

@SuppressWarnings("unchecked")
@Override
public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException 

Source Link

Document

Convenience conversion method that will bind data given JSON tree contains into specific value (usually bean) type.

Usage

From source file:org.jsonschema2pojo.integration.CustomDateTimeFormatIT.java

/**
 * This tests the class generated when formatDateTimes config option is set to FALSE
 * The field should have @JsonFormat annotation with pattern and timezone defined in json schema
 * It also tests the serialization and deserialization process
 * /*from w ww. j a v a  2s .co m*/
 * @throws Exception
 */
@Test
public void testCustomDateTimePatternWithCustomTimezoneWhenFormatDateTimesConfigIsFalse() throws Exception {
    Field field = classWhenConfigIsFalse.getDeclaredField("customFormatCustomTZ");
    JsonFormat annotation = field.getAnnotation(JsonFormat.class);

    assertThat(annotation, notNullValue());
    // Assert that the patterns match
    assertEquals("yyyy-MM-dd", annotation.pattern());
    // Assert that the timezones match
    assertEquals("PST", annotation.timezone());

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setTimeZone(TimeZone.getTimeZone("PST"));

    ObjectNode node = objectMapper.createObjectNode();
    node.put("customFormatCustomTZ", "2016-11-06");

    Object pojo = objectMapper.treeToValue(node, classWhenConfigIsFalse);

    Method getter = new PropertyDescriptor("customFormatCustomTZ", classWhenConfigIsFalse).getReadMethod();

    // Assert that the Date object in the deserialized class is as expected
    assertEquals(dateFormatter.parse("2016-11-06").toString(), getter.invoke(pojo).toString());

    JsonNode jsonVersion = objectMapper.valueToTree(pojo);

    // Assert that when the class is serialized, the date object is serialized as expected 
    assertEquals("2016-11-06", jsonVersion.get("customFormatCustomTZ").asText());
}

From source file:com.yahoo.elide.jsonapi.models.PatchTest.java

@Test
public void testDeserialization() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    String input = "{\"op\":\"add\",\"path\":\"/foo/bar\",\"value\":\"stringValue\"}";
    Patch patch = mapper.readValue(input, Patch.class);

    Assert.assertEquals(patch.getOperation(), Patch.Operation.ADD,
            "Deserialized patch operation should match.");
    Assert.assertEquals(patch.getPath(), "/foo/bar", "Deserialized patch path should match.");

    JsonNode node = patch.getValue();//from   w w  w . jav  a  2s .  c o  m

    String value = mapper.treeToValue(node, String.class);

    Assert.assertEquals(value, "stringValue", "Deserialized patch value should match");
}

From source file:org.jsonschema2pojo.integration.CustomDateTimeFormatIT.java

/**
 * This tests the class generated when formatDateTimes config option is set to TRUE
 * The field should have @JsonFormat annotation with iso8601 date time pattern and UTC timezone
 * It also tests the serialization and deserialization process
 * /*from   w  w  w  .  j  a  v a2s . co  m*/
 * @throws Exception
 */
@Test
public void testDefaultWhenFormatDateTimesConfigIsTrue() throws Exception {
    Field field = classWhenConfigIsTrue.getDeclaredField("defaultFormat");
    JsonFormat annotation = field.getAnnotation(JsonFormat.class);

    assertThat(annotation, notNullValue());
    // Assert that the patterns match
    assertEquals("yyyy-MM-dd'T'HH:mm:ss.SSS", annotation.pattern());
    // Assert that the timezones match
    assertEquals("UTC", annotation.timezone());

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setTimeZone(TimeZone.getTimeZone("UTC"));

    ObjectNode node = objectMapper.createObjectNode();
    node.put("defaultFormat", "2016-11-06T00:00:00.000");

    Object pojo = objectMapper.treeToValue(node, classWhenConfigIsTrue);

    Method getter = new PropertyDescriptor("defaultFormat", classWhenConfigIsTrue).getReadMethod();

    // Assert that the Date object in the deserialized class is as expected
    assertEquals(dateTimeMilliSecFormatter.parse("2016-11-06T00:00:00.000").toString(),
            getter.invoke(pojo).toString());

    JsonNode jsonVersion = objectMapper.valueToTree(pojo);

    // Assert that when the class is serialized, the date object is serialized as expected 
    assertEquals("2016-11-06T00:00:00.000", jsonVersion.get("defaultFormat").asText());
}

From source file:org.jsonschema2pojo.integration.CustomDateTimeFormatIT.java

/**
 * This tests the class generated when formatDateTimes config option is set to TRUE
 * The field should have @JsonFormat annotation with pattern defined in json schema and UTC timezone
 * It also tests the serialization and deserialization process
 * /*from   w  ww  .  jav a  2s  .  co  m*/
 * @throws Exception
 */
@Test
public void testCustomDateTimePatternWithDefaultTimezoneWhenFormatDateTimesConfigIsTrue() throws Exception {
    Field field = classWhenConfigIsTrue.getDeclaredField("customFormatDefaultTZ");
    JsonFormat annotation = field.getAnnotation(JsonFormat.class);

    assertThat(annotation, notNullValue());
    // Assert that the patterns match
    assertEquals("yyyy-MM-dd'T'HH:mm:ss", annotation.pattern());
    // Assert that the timezones match
    assertEquals("UTC", annotation.timezone());

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setTimeZone(TimeZone.getTimeZone("UTC"));

    ObjectNode node = objectMapper.createObjectNode();
    node.put("customFormatDefaultTZ", "2016-11-06T00:00:00");

    Object pojo = objectMapper.treeToValue(node, classWhenConfigIsTrue);

    Method getter = new PropertyDescriptor("customFormatDefaultTZ", classWhenConfigIsTrue).getReadMethod();

    // Assert that the Date object in the deserialized class is as expected
    assertEquals(dateTimeFormatter.parse("2016-11-06T00:00:00").toString(), getter.invoke(pojo).toString());

    JsonNode jsonVersion = objectMapper.valueToTree(pojo);

    // Assert that when the class is serialized, the date object is serialized as expected 
    assertEquals("2016-11-06T00:00:00", jsonVersion.get("customFormatDefaultTZ").asText());
}

From source file:org.jsonschema2pojo.integration.CustomDateTimeFormatIT.java

/**
 * This tests the class generated when formatDateTimes config option is set to FALSE
 * The field should have @JsonFormat annotation with pattern defined in json schema and UTC timezone
 * It also tests the serialization and deserialization process
 * //from ww w  .  j  a v a 2 s .c o  m
 * @throws Exception
 */
@Test
public void testCustomDateTimePatternWithDefaultTimezoneWhenFormatDateTimesConfigIsFalse() throws Exception {
    Field field = classWhenConfigIsFalse.getDeclaredField("customFormatDefaultTZ");
    JsonFormat annotation = field.getAnnotation(JsonFormat.class);

    assertThat(annotation, notNullValue());
    // Assert that the patterns match
    assertEquals("yyyy-MM-dd'T'HH:mm:ss", annotation.pattern());
    // Assert that the timezones match
    assertEquals("UTC", annotation.timezone());

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setTimeZone(TimeZone.getTimeZone("UTC"));

    ObjectNode node = objectMapper.createObjectNode();
    node.put("customFormatDefaultTZ", "2016-11-06T00:00:00");

    Object pojo = objectMapper.treeToValue(node, classWhenConfigIsFalse);

    Method getter = new PropertyDescriptor("customFormatDefaultTZ", classWhenConfigIsFalse).getReadMethod();

    // Assert that the Date object in the deserialized class is as expected
    assertEquals(dateTimeFormatter.parse("2016-11-06T00:00:00").toString(), getter.invoke(pojo).toString());

    JsonNode jsonVersion = objectMapper.valueToTree(pojo);

    // Assert that when the class is serialized, the date object is serialized as expected 
    assertEquals("2016-11-06T00:00:00", jsonVersion.get("customFormatDefaultTZ").asText());
}

From source file:services.plugins.atlassian.jira.jira1.client.JiraService.java

/**
 * Get the configuration (list of status priorities and severities).
 *//*from  ww  w  . ja  va2 s. com*/
public JiraConfig getConfig() throws JiraServiceException {

    JsonNode response = this.callGet(CONFIG_ACTION);

    try {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.treeToValue(response, JiraConfig.class);
    } catch (JsonProcessingException e) {
        throw new JiraServiceException(
                "JiraService/getConfig: error when processing the reponse to JiraConfig.class", e);
    }

}

From source file:services.plugins.atlassian.jira.jira1.client.JiraService.java

/**
 * Get a Jira project by id./*from  www .j a  v  a 2 s .  com*/
 * 
 * @param projectRefId
 *            the Jira project id
 */
public Project getProject(String projectRefId) throws JiraServiceException {

    List<NameValuePair> queryParams = new ArrayList<NameValuePair>();
    queryParams.add(new BasicNameValuePair("projectRefId", projectRefId));

    JsonNode response = this.callGet(GET_PROJECT_ACTION, queryParams);

    try {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.treeToValue(response, Project.class);
    } catch (JsonProcessingException e) {
        throw new JiraServiceException(
                "JiraService/getProject: error when processing the response to Project.class", e);
    }

}

From source file:eu.europa.ec.fisheries.uvms.reporting.service.util.ReportDeserializer.java

private void addFaFilters(JsonNode fa, List<FilterDTO> filterDTOList, Long reportId)
        throws JsonProcessingException {
    if (fa != null) {
        ObjectMapper objectMapper = new ObjectMapper();
        FaFilter faFilter = objectMapper.treeToValue(fa, FaFilter.class);
        FaFilterDTO faFilterDTO = FaFilterDTO.FaFilterBuilder()
                .id(fa.get(ID) != null ? fa.get(ID).longValue() : null).reportId(reportId)
                .reportTypes(faFilter.getReportTypes()).activityTypes(faFilter.getActivityTypes())
                .masters(faFilter.getMasters()).ports(faFilter.getFaPorts()).gears(faFilter.getFaGears())
                .species(faFilter.getSpecies())
                .faWeight(/*w  w  w  . j a  v a2 s. co m*/
                        faFilter.getFaWeight() != null
                                ? new FaWeight(faFilter.getFaWeight().getMin(), faFilter.getFaWeight().getMax(),
                                        faFilter.getFaWeight().getUnit())
                                : null)
                .build();
        filterDTOList.add(faFilterDTO);
    }

}

From source file:com.yahoo.elide.jsonapi.models.PatchTest.java

@Test
public void testListDeserialization() throws Exception {
    ObjectMapper mapper = new ObjectMapper();

    String input = "[{\"op\":\"add\",\"path\":\"/foo/bar\",\"value\":\"stringValue\"}]";

    List<Patch> patches = mapper.readValue(input, new TypeReference<List<Patch>>() {
    });/*from ww  w .  ja v  a  2s. c o  m*/
    Assert.assertEquals(patches.get(0).getOperation(), Patch.Operation.ADD,
            "Deserialized patch operation should match.");
    Assert.assertEquals(patches.get(0).getPath(), "/foo/bar", "Deserialized patch path should match.");

    JsonNode node = patches.get(0).getValue();

    String value = mapper.treeToValue(node, String.class);

    Assert.assertEquals(value, "stringValue", "Deserialized patch value should match");
}

From source file:com.strandls.alchemy.rest.client.exception.ExceptionPayloadDeserializer.java

@SuppressWarnings("unchecked")
@Override//ww  w  .  j  a v a 2s  .co m
public ExceptionPayload deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    final ObjectMapper sourceObjectMapper = ((ObjectMapper) jp.getCodec());

    final ObjectNode tree = jp.readValueAsTree();

    String message = null;
    if (tree.has("exceptionMessage")) {
        message = tree.get("exceptionMessage").asText();
    }

    Throwable exception = null;
    try {
        final String className = tree.get("exceptionClassFQN").asText();
        final Class<? extends Throwable> clazz = (Class<? extends Throwable>) ReflectionUtils
                .forName(className);
        exception = sourceObjectMapper.treeToValue(tree.get("exception"), clazz);
    } catch (final Throwable t) {
        log.warn("Error deserializing exception class", t);
        exception = new InternalServerErrorException(message);
    }

    return new ExceptionPayload(exception.getClass().getName(), message, exception);
}