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

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

Introduction

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

Prototype

@SuppressWarnings({ "unchecked", "resource" })
public <T extends JsonNode> T valueToTree(Object fromValue) throws IllegalArgumentException 

Source Link

Document

Reverse of #treeToValue ; given a value (usually bean), will construct equivalent JSON Tree representation.

Usage

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 and timezone defined in json schema
 * It also tests the serialization and deserialization process
 * //from  w w w  . j ava 2 s.  c  o m
 * @throws Exception
 */
@Test
public void testCustomDateTimePatternWithCustomTimezoneWhenFormatDateTimesConfigIsTrue() throws Exception {
    Field field = classWhenConfigIsTrue.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, classWhenConfigIsTrue);

    Method getter = new PropertyDescriptor("customFormatCustomTZ", classWhenConfigIsTrue).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: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  www.  j  ava  2  s  .c o 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.ikanow.aleph2.shared.crud.mongodb.utils.TestMongoDbUtils.java

@Test
public void updateBeanTest() {

    // Test 1 - getter fields

    final BeanTemplate<TestBean.NestedTestBean> nested1 = BeanTemplateUtils.build(TestBean.NestedTestBean.class)
            .with("nested_string_field", "test1").done(); //(2)
    final UpdateComponent<TestBean> test1 = CrudUtils.update(TestBean.class)
            .add(TestBean::string_fields, "AA", false) //(0)
            .increment(TestBean::long_field, 4) //(1)
            .nested(TestBean::nested_list, CrudUtils.update(nested1) //(2)
                    .unset(TestBean.NestedTestBean::nested_string_field) //(3a)
                    .remove(TestBean.NestedTestBean::nested_string_list, Arrays.asList("x", "y", "z")) //(4)
                    .add(TestBean.NestedTestBean::nested_string_list, "A", true) // (5)
            ).unset(TestBean::bool_field) //(3b)
            .unset(TestBean::nested_object) //(3c)
            .remove(TestBean::nested_list,
                    CrudUtils.allOf(TestBean.NestedTestBean.class).when("nested_string_field", "1")) //6)
            .set(TestBean::enum_field, TestBean.EnumField.test1);

    final DBObject result1 = MongoDbUtils.createUpdateObject(test1);

    final String expected1 = "{ \"$push\" : { \"string_fields\" : \"AA\"} , \"$inc\" : { \"long_field\" : 4} , \"$set\" : { \"nested_list.nested_string_field\" : \"test1\" , \"enum_field\" : \"test1\"} , \"$unset\" : { \"nested_list.nested_string_field\" : 1 , \"bool_field\" : 1 , \"nested_object\" : 1} , \"$pullAll\" : { \"nested_list.nested_string_list\" : [ \"x\" , \"y\" , \"z\"]} , \"$addToSet\" : { \"nested_list.nested_string_list\" : \"A\"} , \"$pull\" : { \"nested_list\" : { \"$and\" : [ { \"nested_string_field\" : \"1\"}]}}}";
    // (see above for analysis of results) 

    assertEquals(expected1, result1.toString());

    // Test 1b - string fields

    final BeanTemplate<TestBean.NestedTestBean> nested1b = BeanTemplateUtils
            .build(TestBean.NestedTestBean.class).with("nested_string_field", "test1").done(); //(2)
    final UpdateComponent<TestBean> test1b = CrudUtils.update(TestBean.class).add("string_fields", "AA", false) //(0)
            .increment("long_field", 4) //(1)
            .nested("nested_list", CrudUtils.update(nested1b) //(2)
                    .unset("nested_string_field") //(3a)
                    .remove("nested_string_list", Arrays.asList("x", "y", "z")) //(4)
                    .add("nested_string_list", "A", true) // (5)
            ).unset("bool_field") //(3b)
            .unset("nested_object") //(3c)
            .remove("nested_list",
                    CrudUtils.allOf(TestBean.NestedTestBean.class).when("nested_string_field", "1")) //6)
    ;// w w  w. ja  v a2  s.  c om

    final DBObject result1b = MongoDbUtils.createUpdateObject(test1b);

    final String expected1b = "{ \"$push\" : { \"string_fields\" : \"AA\"} , \"$inc\" : { \"long_field\" : 4} , \"$set\" : { \"nested_list.nested_string_field\" : \"test1\"} , \"$unset\" : { \"nested_list.nested_string_field\" : 1 , \"bool_field\" : 1 , \"nested_object\" : 1} , \"$pullAll\" : { \"nested_list.nested_string_list\" : [ \"x\" , \"y\" , \"z\"]} , \"$addToSet\" : { \"nested_list.nested_string_list\" : \"A\"} , \"$pull\" : { \"nested_list\" : { \"$and\" : [ { \"nested_string_field\" : \"1\"}]}}}";
    // (see above for analysis of results) 

    assertEquals(expected1b, result1b.toString());

    // Test2 - more coverage

    final BeanTemplate<TestBean> testbean2 = BeanTemplateUtils.build(TestBean.class)
            .with(TestBean::map, ImmutableMap.<String, String>builder().put("a", "b").build()).done();

    final UpdateComponent<TestBean> test2 = CrudUtils.update(testbean2) //(3)
            .set(TestBean::string_fields, "A").add(TestBean::string_fields, Arrays.asList("a", "b", "c"), true) //(1)
            .set("long_field", 1L).nested("nested_list", CrudUtils.update(TestBean.NestedTestBean.class)
                    .add(TestBean.NestedTestBean::nested_string_list, "A", false) // (will be overwritten)
            ).add("nested_list.nested_string_list", Arrays.asList("x", "y"), false); //(2)

    final DBObject result2 = MongoDbUtils.createUpdateObject(test2);

    final String expected2 = "{ \"$set\" : { \"string_fields\" : \"A\" , \"long_field\" : 1 , \"map\" : { \"a\" : \"b\"}} , \"$addToSet\" : { \"string_fields\" : { \"$each\" : [ \"a\" , \"b\" , \"c\"]}} , \"$push\" : { \"nested_list.nested_string_list\" : { \"$each\" : [ \"x\" , \"y\"]}}}";
    // (see above for analysis of results) 

    assertEquals(expected2, result2.toString());

    // Test3 - delete object

    final UpdateComponent<TestBean> test3 = CrudUtils.update(TestBean.class).deleteObject();

    final DBObject result3 = MongoDbUtils.createUpdateObject(test3);

    assertEquals("{ \"$unset\" :  null }", result3.toString());

    // Test4 - bean templates as JsonNode (see _json for the other way round!)

    final BeanTemplate<TestBean.NestedTestBean> nested4a = BeanTemplateUtils
            .build(TestBean.NestedTestBean.class).with("nested_string_field", "test4a").done(); //(2)

    final BeanTemplate<TestBean.NestedTestBean> nested4b = BeanTemplateUtils
            .build(TestBean.NestedTestBean.class).with("nested_string_field", "test4b").done(); //(2)

    //convert to JsonNode:
    final ObjectMapper object_mapper = MongoJackModule
            .configure(BeanTemplateUtils.configureMapper(Optional.empty()));
    JsonNode nested4a_json = object_mapper.valueToTree(nested4a.get());
    JsonNode nested4b_json = object_mapper.valueToTree(nested4b.get());

    final UpdateComponent<TestBean> test4 = CrudUtils.update(TestBean.class)
            .set(TestBean::nested_object, nested4a_json)
            .add(TestBean::nested_list, Arrays.asList(nested4a_json, nested4b_json), false);

    final DBObject result4 = MongoDbUtils.createUpdateObject(test4);

    assertEquals(
            "{ \"$set\" : { \"nested_object\" : { \"nested_string_field\" : \"test4a\"}} , \"$push\" : { \"nested_list\" : { \"$each\" : [ { \"nested_string_field\" : \"test4a\"} , { \"nested_string_field\" : \"test4b\"}]}}}",
            result4.toString());
}

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 ww  w .  ja v  a2s. c o  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  . jav  a2 s . com*/
 * @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: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  ww .  ja va 2s.c o  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:de.upb.wdqa.wdvd.test.JsonNormalizerTest.java

@Test
public void testNormalizedJsonParsing2() throws IOException {
    String jsonString = readFile("src/test/resources/oldJson02.json", StandardCharsets.UTF_8);

    ObjectMapper mapper = new ObjectMapper();
    OldJacksonItemDocument oldDoc = mapper.readValue(jsonString, OldJacksonItemDocument.class);

    Assert.assertNotNull(oldDoc.getLabels());
    Assert.assertNotNull(oldDoc.getDescriptions());
    Assert.assertNotNull(oldDoc.getAliases());
    Assert.assertNotNull(oldDoc.getClaims());
    Assert.assertNotNull(oldDoc.getSiteLinks());

    JacksonItemDocument doc = JsonNormalizer.normalizeFormat(oldDoc);

    Assert.assertNotNull(doc.getLabels());
    Assert.assertNotNull(doc.getDescriptions());
    Assert.assertNotNull(doc.getAliases());
    Assert.assertNotNull(doc.getJsonClaims());
    Assert.assertNotNull(doc.getSiteLinks());

    JsonNode node = mapper.valueToTree(doc);
    mapper.readValue(mapper.treeAsTokens(node), JacksonItemDocument.class);
}

From source file:org.commonwl.view.cwl.CWLService.java

/**
 * Converts a yaml String to JsonNode//from  w w  w . j  ava 2 s . com
 * @param yaml A String containing the yaml content
 * @return A JsonNode with the content of the document
 */
private JsonNode yamlStringToJson(String yaml) {
    Yaml reader = new Yaml();
    ObjectMapper mapper = new ObjectMapper();
    return mapper.valueToTree(reader.load(yaml));
}