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

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

Introduction

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

Prototype

public JsonNode readTree(URL source) throws IOException, JsonProcessingException 

Source Link

Document

Method to deserialize JSON content as tree expressed using set of JsonNode instances.

Usage

From source file:org.jboss.pnc.buildagent.server.TestGetRunningProcesses.java

private JsonNode readResponse(HttpURLConnection connection) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readTree(connection.getInputStream());
}

From source file:io.cloudslang.content.json.actions.ArraySize.java

/**
 * This operation determines the number of elements in the given JSON array.  If an element
 * is itself another JSON array, it only counts as 1 element; in other
 * words, it will not expand and count embedded arrays.  Null values are also
 * considered to be an element.//from   www. j  a  v  a 2 s  .c  o m
 *
 * @param array The string representation of a JSON array object.
 * @return a map containing the output of the operation. Keys present in the map are:
 * <p/>
 * <br><br><b>returnResult</b> - This will contain size of the json array given in the input.
 * <br><b>exception</b> - In case of success response, this result is empty. In case of failure response,
 * this result contains the java stack trace of the runtime exception.
 * <br><br><b>returnCode</b> - The returnCode of the operation: 0 for success, -1 for failure.
 */
@Action(name = "Array Size", outputs = { @Output(OutputNames.RETURN_RESULT), @Output(OutputNames.RETURN_CODE),
        @Output(OutputNames.EXCEPTION) }, responses = {
                @Response(text = ResponseNames.SUCCESS, field = OutputNames.RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED),
                @Response(text = ResponseNames.FAILURE, field = OutputNames.RETURN_CODE, value = ReturnCodes.FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) })
public Map<String, String> execute(@Param(value = Constants.InputNames.ARRAY, required = true) String array) {

    Map<String, String> returnResult = new HashMap<>();

    if (StringUtilities.isBlank(array)) {
        return populateResult(returnResult, new Exception(NOT_A_VALID_JSON_ARRAY_MESSAGE));
    }
    JsonNode jsonNode;
    try {
        ObjectMapper mapper = new ObjectMapper();
        jsonNode = mapper.readTree(array);
    } catch (IOException exception) {
        final String value = "Invalid jsonObject provided! " + exception.getMessage();
        return populateResult(returnResult, value, exception);
    }
    final String result;
    if (jsonNode instanceof ArrayNode) {
        final ArrayNode asJsonArray = (ArrayNode) jsonNode;
        result = Integer.toString(asJsonArray.size());
    } else {
        return populateResult(returnResult, new Exception(NOT_A_VALID_JSON_ARRAY_MESSAGE));
    }
    return populateResult(returnResult, result, null);
}

From source file:com.gsma.mobileconnect.discovery.DiscoveryResponseTest.java

private JsonNode buildJsonObject() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readTree("{ \"field\": \"value\" }");
}

From source file:com.crossedstreams.desktop.website.JsonParser.java

/**
 * Parse JSON formatted input./*from  w ww .ja va 2 s.co  m*/
 * 
 * @param from JSON formatted data as a reader stream
 * @return collection build from incoming data
 * @throws IOException if the attempt to read the input fails
 */
public Collection<UrlGroup> parseUrlGroups(Reader from) throws IOException {
    ObjectMapper jsonObjectMapper = new ObjectMapper();
    JsonNode rootNode = jsonObjectMapper.readTree(from);

    List<UrlGroup> urlGroups = new ArrayList<UrlGroup>();
    if (!rootNode.isArray())
        throw new IllegalArgumentException("Invalid input, root node should be an array of groups");
    for (JsonNode groupJson : rootNode) {
        urlGroups.add(buildGroup(groupJson));
    }
    return urlGroups;
}

From source file:com.netflix.zeno.json.JsonSerializationFramework.java

public <T> T deserializeJson(String type, String json) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper.readTree(json);
    NFTypeSerializer<T> serializer = getSerializer(type);
    JsonReadGenericRecord readRecord = new JsonReadGenericRecord(serializer.getFastBlobSchema(), node);
    T object = serializer.deserialize(readRecord);

    return object;
}

From source file:net.sf.taverna.t2.activities.wsdl.xmlsplitter.XMLInputSplitterActivityFactory.java

@Override
public JsonNode getActivityConfigurationSchema() {
    ObjectMapper objectMapper = new ObjectMapper();
    try {/*  www . j  a  v  a 2  s  .  c  o m*/
        return objectMapper.readTree(getClass().getResource("/xml-splitter.schema.json"));
    } catch (IOException e) {
        return objectMapper.createObjectNode();
    }
}

From source file:com.basistech.dm.osgitest.BundleIT.java

@Test
public void jsonWorksABit() throws Exception {
    List<Name> names = Lists.newArrayList();
    Name.Builder builder = new Name.Builder("Fred");
    names.add(builder.build());// w  w w  .ja  va2  s. co m
    builder = new Name.Builder("George");
    builder.languageOfOrigin(LanguageCode.ENGLISH).script(ISO15924.Latn).languageOfUse(LanguageCode.FRENCH);
    names.add(builder.build());
    ObjectMapper mapper = objectMapper();
    String json = mapper.writeValueAsString(names);
    // one way to inspect the works is to read it back in _without_ our customized mapper.
    ObjectMapper plainMapper = new ObjectMapper();
    JsonNode tree = plainMapper.readTree(json);
    Assert.assertTrue(tree.isArray());
    Assert.assertEquals(2, tree.size());
    JsonNode node = tree.get(0);
    Assert.assertTrue(node.has("text"));
    Assert.assertEquals("Fred", node.get("text").asText());
    Assert.assertFalse(node.has("script"));
    Assert.assertFalse(node.has("languageOfOrigin"));
    Assert.assertFalse(node.has("languageOfUse"));

    List<Name> readBack = mapper.readValue(json, new TypeReference<List<Name>>() {
    });
    Assert.assertEquals(names, readBack);
}

From source file:de.qaware.cloud.deployer.kubernetes.resource.deployment.DeploymentLabelUtilTest.java

public void testAddLabel() throws IOException, ResourceException, ResourceConfigException {
    // Add new label
    DeploymentLabelUtil.addLabel(resourceConfig, "test", "test");

    // Read marked deployment
    String markedDeployment = FileUtil.readFileContent(getTestFilePath("deployment-marked.yml"));

    // Check result
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    JsonNode contentTree = mapper.readTree(resourceConfig.getContent());
    JsonNode expectedContentTree = mapper.readTree(markedDeployment);
    assertEquals(expectedContentTree, contentTree);
}

From source file:org.jclouds.openstack.poppy.v1.mapbinders.JSONPatchUpdate.java

@Override
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {
    String jsonPatch = null;//from w ww. java  2 s  .  co m
    Service service = (Service) postParams.get("service");

    //Json json = Guice.createInjector(new GsonModule()).getInstance(Json.class);

    String targetService = json.toJson(postParams.get("updateService"));
    String sourceService = json.toJson(service.toUpdatableService().build());

    ObjectMapper mapper = new ObjectMapper();
    try {
        jsonPatch = JsonDiff.asJson(mapper.readTree(sourceService), mapper.readTree(targetService)).toString();
    } catch (IOException e) {
        throw new RuntimeException("Could not create a JSONPatch", e);
    }

    return bindToRequest(request, (Object) jsonPatch);
}

From source file:org.apache.tika.language.translate.GoogleTranslator.java

@Override
public String translate(String text, String sourceLanguage, String targetLanguage) throws Exception {
    if (!this.isAvailable)
        return text;
    Response response = client.accept(MediaType.APPLICATION_JSON).query("key", apiKey)
            .query("source", sourceLanguage).query("target", targetLanguage).query("q", text).get();
    BufferedReader reader = new BufferedReader(
            new InputStreamReader((InputStream) response.getEntity(), "UTF-8"));
    String line = null;// ww  w  . j  av  a  2s .  c  o m
    StringBuffer responseText = new StringBuffer();
    while ((line = reader.readLine()) != null) {
        responseText.append(line);
    }

    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonResp = mapper.readTree(responseText.toString());
    return jsonResp.findValuesAsText("translatedText").get(0);
}