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:com.bna.ezrxlookup.util.JsonMapperUtil.java

/**
 * Parse JSON string and return a list of object type.
 * @param jsonString - input JSON string
 * @param rootName - root node name//  w ww  .  j a v  a 2  s  . c  o  m
 * @param type - object class type
 * @return list of object class
 */
public static <T> List<T> readJsonToList(String jsonString, String rootName, Class<T> clazz) throws Exception {
    List<T> objList = null;
    ObjectMapper objectMapper = new ObjectMapper();

    try {
        // get json content with root name
        JsonNode root = objectMapper.readTree(jsonString).get(rootName);
        TypeFactory tf = objectMapper.getTypeFactory();
        JavaType listOfObjs = tf.constructCollectionType(ArrayList.class, clazz);
        objList = objectMapper.readValue(root.traverse(), listOfObjs);
    } catch (Exception e) {
        throw e;
    }

    return objList;
}

From source file:org.opendaylight.atrium.hostservice.impl.ConfigReader.java

public static boolean initialize(URL configFileUrl) {
    byte[] jsonData = null;
    if (configFileUrl != null) {
        try {//ww  w.j  a v a2  s  . c o m
            InputStream input = configFileUrl.openStream();
            jsonData = IOUtils.toByteArray(input);
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        rootJsonNode = objectMapper.readTree(jsonData);
    } catch (IOException e) {
        return false;
    }
    return true;
}

From source file:ro.fortsoft.matilda.util.RecaptchaUtils.java

public static boolean verify(String recaptchaResponse, String secret) {
    if (StringUtils.isNullOrEmpty(recaptchaResponse)) {
        return false;
    }/*from ww  w. j av  a 2s .  c o  m*/

    boolean result = false;
    try {
        URL url = new URL("https://www.google.com/recaptcha/api/siteverify");
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        // add request header
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
        connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String postParams = "secret=" + secret + "&response=" + recaptchaResponse;
        //            log.debug("Post parameters '{}'", postParams);

        // send post request
        connection.setDoOutput(true);
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(postParams);
        outputStream.flush();
        outputStream.close();

        int responseCode = connection.getResponseCode();
        log.debug("Response code '{}'", responseCode);

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();

        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        // print result
        log.debug("Response '{}'", response.toString());

        // parse JSON response and return 'success' value
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(response.toString());
        JsonNode nameNode = rootNode.path("success");

        result = nameNode.asBoolean();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    return result;
}

From source file:org.mascherl.session.MascherlSession.java

private static ObjectNode parseJson(String json, ObjectMapper objectMapper) {
    try {/*  w  ww  .j  a  va2 s.  c o m*/
        return (ObjectNode) objectMapper.readTree(json);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.fcrepo.camel.indexing.solr.integration.TestUtils.java

public static Callable<Integer> solrCount(final String url) {
    final ObjectMapper mapper = new ObjectMapper();

    return new Callable<Integer>() {
        public Integer call() throws Exception {
            return mapper.readTree(httpGet(url)).get("response").get("numFound").asInt();
        }//w  ww.ja v a2 s.c o  m
    };
}

From source file:com.mirth.connect.client.ui.components.rsta.AutoCompleteProperties.java

static AutoCompleteProperties fromJSON(String autoCompleteJSON) {
    Boolean activateAfterLetters = null;
    String activateAfterOthers = null;
    Integer activationDelay = null;

    if (StringUtils.isNotBlank(autoCompleteJSON)) {
        try {/*from w ww.  jav a2s .  c  o m*/
            ObjectMapper mapper = new ObjectMapper();
            ObjectNode rootNode = (ObjectNode) mapper.readTree(autoCompleteJSON);

            JsonNode node = rootNode.get("activateAfterLetters");
            if (node != null) {
                activateAfterLetters = node.asBoolean();
            }

            node = rootNode.get("activateAfterOthers");
            if (node != null) {
                activateAfterOthers = node.asText();
            }

            node = rootNode.get("activationDelay");
            if (node != null) {
                activationDelay = node.asInt();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return new AutoCompleteProperties(activateAfterLetters, activateAfterOthers, activationDelay);
}

From source file:au.org.ands.vocabs.toolkit.db.TaskUtils.java

/** Parse a string containing JSON into a JsonNode.
 * @param jsonString The String in JSON format to be converted
 * @return The resulting JSON structure/*from  ww  w. ja v a2  s. c  o m*/
 */
public static JsonNode jsonStringToTree(final String jsonString) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.readTree(jsonString);
    } catch (IOException e) {
        logger.error("Exception in jsonStringToTree", e);
        return null;
    }
}

From source file:controllers.IntegrationTest.java

private static void assertPretty(Result result) {
    String contentAsString = contentAsString(result);
    ObjectMapper mapper = new ObjectMapper();
    try {/*  ww  w.  j a va2  s .  co  m*/
        JsonNode jsonNode = mapper.readTree(contentAsString);
        String prettyString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
        assertThat(contentAsString).isEqualTo(prettyString);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.indeed.imhotep.web.QueryMetadata.java

public static QueryMetadata fromJSON(String json) {
    final QueryMetadata metadataObject = new QueryMetadata();
    final ObjectMapper mapper = new ObjectMapper();
    try {//  w  w  w. ja  v  a  2 s .co m
        final JsonNode root = mapper.readTree(json);
        final Iterator<Map.Entry<String, JsonNode>> nodeIterator = root.fields();
        while (nodeIterator.hasNext()) {
            Map.Entry<String, JsonNode> item = nodeIterator.next();
            metadataObject.addItem(item.getKey(), item.getValue().textValue());
        }
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
    return metadataObject;
}

From source file:io.github.robwin.swagger.loader.Swagger20Parser.java

private static Swagger convertToSwagger(String data) throws IOException {
    ObjectMapper mapper;
    if (data.trim().startsWith("{")) {
        mapper = Json.mapper();/*from   ww w  .j  a  v a 2 s  .co  m*/
    } else {
        mapper = Yaml.mapper();
    }
    JsonNode rootNode = mapper.readTree(data);
    // must have swagger node set
    JsonNode swaggerNode = rootNode.get("swagger");
    if (swaggerNode == null) {
        throw new IllegalArgumentException("Swagger String has an invalid format.");
    } else {
        return mapper.convertValue(rootNode, Swagger.class);
    }
}