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

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

Introduction

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

Prototype

@Override
public ObjectNode createObjectNode() 

Source Link

Document

Note: return type is co-variant, as basic ObjectCodec abstraction can not refer to concrete node types (as it's part of core package, whereas impls are part of mapper package)

Usage

From source file:com.gsma.mobileconnect.utils.JsonUtilsTest.java

@Test
public void extractUrl_withNoRelField_shouldReturnUrl() {
    // GIVEN/* w  w w .ja va  2  s.co  m*/
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode root = mapper.createObjectNode();
    ArrayNode links = mapper.createArrayNode();
    root.set("links", links);

    ObjectNode link = mapper.createObjectNode();
    link.put("href", "href");

    links.add(link);

    // WHEN
    String url = JsonUtils.extractUrl(root, "relToFind");

    // THEN
    assertNull(url);
}

From source file:com.gsma.mobileconnect.utils.JsonUtilsTest.java

@Test
public void extractUrl_withUrl_shouldReturnUrl() {
    // GIVEN//w  w  w.java 2  s  .c o  m
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode root = mapper.createObjectNode();
    ArrayNode links = mapper.createArrayNode();
    root.set("links", links);

    ObjectNode link = mapper.createObjectNode();
    String relToFind = "relToFind";
    link.put("rel", relToFind);
    String expectedHref = "hrefToFind";
    link.put("href", expectedHref);

    links.add(link);

    // WHEN
    String url = JsonUtils.extractUrl(root, relToFind);

    // THEN
    assertEquals(expectedHref, url);
}

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 www .  java 2s  . 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 TRUE
 * The field should have @JsonFormat annotation with pattern and timezone defined in json schema
 * It also tests the serialization and deserialization process
 * // w w  w  .j av  a2 s  .  c  om
 * @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 defined in json schema and UTC timezone
 * It also tests the serialization and deserialization process
 * /*from   w w w  .  j  a  v a 2  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 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 w w. j  av  a  2  s  .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: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.j  a  va 2s . 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.onosproject.EvacuateCommand.java

private ObjectNode json(ObjectMapper mapper, Device device, List<FlowEntry> flows) {
    ObjectNode result = mapper.createObjectNode();
    ArrayNode array = mapper.createArrayNode();

    flows.forEach(flow -> array.add(jsonForEntity(flow, FlowEntry.class)));

    result.put("device", device.id().toString()).put("flowCount", flows.size()).set("flows", array);
    return result;
}

From source file:org.dswarm.graph.xml.test.XMLResourceTest.java

private void readXMLFromDB(final String recordClassURI, final String dataModelURI,
        final Optional<String> optionalRootAttributePath, final Optional<String> optionalRecordTag,
        final Optional<Integer> optionalVersion, final Optional<String> optionalOriginalDataType,
        final String expectedFileName) throws IOException {

    final ObjectMapper objectMapper = Util.getJSONObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    final ObjectNode requestJson = objectMapper.createObjectNode();

    requestJson.put(DMPStatics.RECORD_CLASS_URI_IDENTIFIER, recordClassURI);
    requestJson.put(DMPStatics.DATA_MODEL_URI_IDENTIFIER, dataModelURI);

    if (optionalRootAttributePath.isPresent()) {

        requestJson.put(DMPStatics.ROOT_ATTRIBUTE_PATH_IDENTIFIER, optionalRootAttributePath.get());
    }//from  w  w w.  j a v  a 2s  .  co  m

    if (optionalRecordTag.isPresent()) {

        requestJson.put(DMPStatics.RECORD_TAG_IDENTIFIER, optionalRecordTag.get());
    }

    if (optionalVersion.isPresent()) {

        requestJson.put(DMPStatics.VERSION_IDENTIFIER, optionalVersion.get());
    }

    if (optionalOriginalDataType.isPresent()) {

        requestJson.put(DMPStatics.ORIGINAL_DATA_TYPE_IDENTIFIER, optionalOriginalDataType.get());
    }

    final String requestJsonString = objectMapper.writeValueAsString(requestJson);

    // POST the request
    final ClientResponse response = target().path("/get").type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_XML_TYPE).post(ClientResponse.class, requestJsonString);

    Assert.assertEquals("expected 200", 200, response.getStatus());
    Assert.assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());

    final InputStream actualXMLStream = response.getEntity(InputStream.class);
    Assert.assertNotNull(actualXMLStream);

    // compare result with expected result
    final URL expectedFileURL = Resources.getResource(expectedFileName);
    final String expectedXML = Resources.toString(expectedFileURL, Charsets.UTF_8);

    final BufferedInputStream bis = new BufferedInputStream(actualXMLStream, 1024);

    // do comparison: check for XML similarity
    final Diff xmlDiff = DiffBuilder.compare(Input.fromString(expectedXML)).withTest(Input.fromStream(bis))
            .ignoreWhitespace().checkForSimilar().build();

    if (xmlDiff.hasDifferences()) {
        final StringBuilder sb = new StringBuilder("Oi chap, there seem to ba a mishap!");
        for (final Difference difference : xmlDiff.getDifferences()) {
            sb.append('\n').append(difference);
        }
        Assert.fail(sb.toString());
    }

    actualXMLStream.close();
    bis.close();
}

From source file:scott.barleyrs.rest.AdminService.java

@GET
@Path("/entitytypes/")
@Produces(MediaType.APPLICATION_JSON)/*from  w  w w. j  a  v a 2s  . c o  m*/
public JsonNode listEntityTypes() {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode result = mapper.createArrayNode();
    for (Definitions defs : env.getDefinitionsSet().getDefinitions()) {
        for (EntityType entityType : defs.getEntityTypes()) {
            ObjectNode et = mapper.createObjectNode();
            et.put("namespace", defs.getNamespace());
            et.put("fqn", entityType.getInterfaceName());
            et.put("simpleName", entityType.getInterfaceShortName());
            result.add(et);
        }
    }
    return result;
}