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.meli.client.controller.AppController.java

private static void doApiCalls(String query, String countryCode) {
        List<Item> items = new ArrayList<Item>();
        Random r = new Random();

        Meli meliOb = new Meli(2072832875526076L, "1VZEFfhbSCy3vDDrh0Dp96NkfgNOWPGq");
        try {//from w ww.  j  a  va 2  s.  c  o m

            FluentStringsMap params = new FluentStringsMap();
            params.add("q", query);

            String path = countryCode.isEmpty() ? "/sites/MLA/search/" : "/sites/" + countryCode + "/search";
            Response response = meliOb.get(path, params);

            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(response.getResponseBody());
            JsonNode resultNode = rootNode.findPath("results");

            if (resultNode.size() > 0) {
                JsonNode currNode = null;
                JsonNode dupNode = null;
                boolean dupNodeVal = false;

                CloseableHttpClient httpClient = HttpClientBuilder.create().build();

                Item item = null;

                int randomMins;

                String checkDupsUrl = null;

                HttpGet get = null;
                URIBuilder builder = null;
                URI uri = null;

                for (int i = 0; i < resultNode.size(); i++) {
                    currNode = resultNode.get(i);

                    builder = new URIBuilder();
                    builder.setScheme("http").setHost(apiUrl).setPath("/api/proxy/check")
                            .setParameter("host", "test").setParameter("itemID", currNode.get("id").asText());
                    uri = builder.build();

                    get = new HttpGet(uri);
                    get.addHeader("accept", "application/json");

                    CloseableHttpResponse res = httpClient.execute(get);
                    BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
                    String content = "", line;

                    while ((line = br.readLine()) != null) {
                        content = content + line;
                    }

                    if (!content.isEmpty()) {
                        dupNode = objectMapper.readTree(content);
                        dupNodeVal = Boolean.parseBoolean(dupNode.get("isDuplicate").asText());

                        if (dupNodeVal && !allowDuplicates)
                            continue;

                        item = new Item(query, currNode.get("id").asText(), "", //currNode.get("host").asText(),?? 
                                currNode.get("site_id").asText(), currNode.get("title").asText(),
                                currNode.get("permalink").asText(), currNode.get("category_id").asText(),
                                currNode.get("seller").get("id").asText(), "", //currNode.get("seller").get("name").asText()
                                "", //currNode.get("seller").get("link").asText()
                                "", //currNode.get("seller").get("email").asText()
                                currNode.get("price").asText(), "", //currNode.get("auction_price").asText(),
                                "", //currNode.get("currency_id").asText(),
                                currNode.get("thumbnail").asText());
                        items.add(item);
                    }
                    randomMins = (int) (Math.random() * (maxWaitTime - minWaitTime)) + minWaitTime;
                    Thread.sleep(randomMins);
                }

                if (!items.isEmpty()) {
                    HttpPost post = new HttpPost(apiUrl + "/proxy/add");
                    StringEntity stringEntity = new StringEntity(objectMapper.writeValueAsString(items));

                    post.setEntity(stringEntity);
                    post.setHeader("Content-type", "application/json");

                    CloseableHttpResponse postResponse = httpClient.execute(post);
                    System.out.println("this is the reponse of the final request: "
                            + postResponse.getStatusLine().getStatusCode());
                }
            }

        } catch (MeliException ex) {
            Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (URISyntaxException ex) {
            Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

From source file:org.primaldev.ppm.util.ChartTypeGenerator.java

protected static JsonNode convert(byte[] jsonBytes) {
    try {/*www . j  ava2 s  .c  om*/
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readTree(jsonBytes);
    } catch (Exception e) {
        throw new ActivitiException("Report dataset contains invalid json", e);
    }
}

From source file:com.google.api.tools.framework.importers.swagger.MultiSwaggerParser.java

private static Map<String, File> getTopLevelSwaggerFiles(Map<String, FileWrapper> savedFiles)
        throws SwaggerConversionException {
    ImmutableMap.Builder<String, File> topLevelFiles = ImmutableMap.builder();
    for (Entry<String, FileWrapper> savedFile : savedFiles.entrySet()) {

        try {/*  www  .j  av  a 2s .  c  o  m*/
            String inputFileContent = savedFile.getValue().getFileContents().toStringUtf8();
            File inputFile = new File(savedFile.getValue().getFilename());
            ObjectMapper objMapper = createObjectMapperForExtension(inputFile);
            JsonNode data = objMapper.readTree(inputFileContent);

            if (isTopLevelSwaggerFile(data)) {
                validateSwaggerSpec(data);
                topLevelFiles.put(savedFile.getKey(), inputFile);
            }
        } catch (IOException ex) {
            throw new SwaggerConversionException("Unable to parse the content. " + ex.getMessage(), ex);
        }
    }
    return topLevelFiles.build();
}

From source file:com.infinities.keystone4j.utils.JsonUtils.java

public static JsonNode convertToJsonNode(String text) throws JsonProcessingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getFactory(); // since 2.1 use
    // mapper.getFactory()
    // instead/*from   w  w  w .  j  a v  a 2 s . c  om*/
    JsonParser jp = factory.createParser(text);
    JsonNode node = mapper.readTree(jp);
    return node;
}

From source file:org.brutusin.json.impl.JacksonSchema.java

private static com.fasterxml.jackson.databind.JsonNode load(String schema, ObjectMapper mapper)
        throws ParseException {
    if (schema == null || schema.trim().isEmpty()) {
        return null;
    }//  ww w  .  j  a v  a2s  .c om
    try {
        return mapper.readTree(JacksonCodec.addVersion(schema));
    } catch (JsonProcessingException ex) {
        throw new ParseException(ex);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:au.org.ands.vocabs.toolkit.test.arquillian.ArquillianTestUtils.java

/** Compare two files containing JSON, asserting that they contain
 * the same content./*from  www. j  a va  2 s.c om*/
 * @param testFilename The filename of the file containing the generated
 *      content. An TestNG assertion is made that this file exists.
 * @param correctFilename The filename of the file containing the correct
 *      value.
 * @throws IOException If reading either file fails.
 */
public static void compareJson(final String testFilename, final String correctFilename) throws IOException {
    File testFile = new File(testFilename);
    FileAssert.assertFile(testFile, "Test file (" + testFilename + ") is not " + "a proper file");
    ObjectMapper mapper = new ObjectMapper();
    JsonNode testJson;
    JsonNode correctJson;
    // IOException not caught here, but allowed to propagate.
    testJson = mapper.readTree(new File(testFilename));
    correctJson = mapper.readTree(new File(correctFilename));
    Assert.assertEquals(testJson, correctJson);
    // NB This uses a top-level equality test done by TestNG.
    // There is also a top-level equality test implemented by Jackson:
    // correctJson.equals(testJson). The TestNG one seems to give
    // the same end result, but gives better diagnostics in case
    // a difference is found.
}

From source file:com.msopentech.odatajclient.testservice.utils.Commons.java

public static InputStream changeFormat(final InputStream is, final Accept target) {
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {/*from   www . j  a va  2  s.  c  om*/
        IOUtils.copy(is, bos);
        IOUtils.closeQuietly(is);

        final ObjectMapper mapper = new ObjectMapper();
        final JsonNode node = changeFormat(
                (ObjectNode) mapper.readTree(new ByteArrayInputStream(bos.toByteArray())), target);

        return IOUtils.toInputStream(node.toString());
    } catch (Exception e) {
        LOG.error("Error changing format", e);
        return new ByteArrayInputStream(bos.toByteArray());
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:gate.corpora.twitter.TweetUtils.java

public static List<Tweet> readTweetStrings(String[] lines, List<String> contentKeys, List<String> featureKeys)
        throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    List<Tweet> tweets = new ArrayList<Tweet>();

    for (String line : lines) {
        if (line.length() > 0) {
            JsonNode jnode = mapper.readTree(line);
            tweets.add(Tweet.readTweet(jnode, contentKeys, featureKeys));
        }//from  w  w w  . j  a  va 2s  . c o m
    }

    return tweets;
}

From source file:gate.corpora.twitter.TweetUtils.java

public static List<Tweet> readTweetStrings(List<String> lines, List<String> contentKeys,
        List<String> featureKeys) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    List<Tweet> tweets = new ArrayList<Tweet>();

    for (String line : lines) {
        if (line.length() > 0) {
            JsonNode jnode = mapper.readTree(line);
            tweets.add(Tweet.readTweet(jnode, contentKeys, featureKeys));
        }//from   w  w  w .  j a v a2 s .co m
    }

    return tweets;
}

From source file:nl.esciencecenter.xnatclient.data.XnatParser.java

/**
 * Xnat Rest Query has a diferrent Json Tree. Parse structure
 * /*from w w w . j  a  v  a  2  s. c om*/
 * @throws XnatParseException
 */
public static int parseJsonQueryResult(XnatObjectType type, String jsonStr, List list)
        throws XnatParseException {
    if (StringUtil.isEmpty(jsonStr))
        return 0;

    try {
        JsonFactory jsonFac = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper();

        // use dom like parsing:
        JsonNode tree = mapper.readTree(jsonStr);

        JsonNode items = tree.get("items");

        if (items == null) {
            logger.warnPrintf("Couldn't find 'items' in jsonTree\n");
            return 0;
        }

        // parse objects:
        JsonNode node = null;
        Iterator<JsonNode> els = items.elements();
        int index = 0;
        while (els.hasNext()) {
            logger.debugPrintf(" - item[%d]\n", index++);
            JsonNode el = els.next();
            node = el.get("data_fields");
            if (node != null)
                list.add(parseXnatObject(type, node));
            else
                logger.warnPrintf("jsonNode doesn't have 'data_fields' element:%s", el);
        }
    }
    // wrap exception:
    catch (JsonParseException e) {
        throw new XnatParseException("JsonParseException:" + e.getMessage(), e);
    } catch (IOException e) {
        throw new XnatParseException("IOException:" + e.getMessage(), e);
    }

    return list.size();
}