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:nl.esciencecenter.xnatclient.data.XnatParser.java

public static int parseJsonResult(XnatObjectType type, String jsonStr, List list) throws XnatParseException {
    if (StringUtil.isEmpty(jsonStr))
        return 0;
    try {//from w ww. jav  a2 s.c om
        JsonFactory jsonFac = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper();

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

        JsonNode resultSet = tree.get("ResultSet");
        if (resultSet == null) {
            logger.warnPrintf("Couldn't find 'ResultSet' in jsonTree\n");
            // return 0;
        }

        JsonNode result = resultSet.get("Result");
        if (result == null) {
            logger.warnPrintf("Couldn't find 'Result' in jsonTree\n");
            return 0;
        }

        if (result.isArray() == false) {
            // logger.warnPrintf("Couldn't find 'Result' in jsonTree\n");
            return 0;
        }
        rootNode = result;

        // parse objects:
        Iterator<JsonNode> els = rootNode.elements();
        while (els.hasNext()) {
            JsonNode el = els.next();
            list.add(parseXnatObject(type, el));
        }
    }
    // wrap exception:
    catch (JsonParseException e) {
        throw new XnatParseException("Couldn't parse result:\n" + jsonStr + "\n---\n" + e.getMessage(), e);
    } catch (IOException e) {
        throw new XnatParseException("IOException:" + e.getMessage(), e);
    }

    return list.size();
}

From source file:com.graphaware.test.util.TestUtils.java

/**
 * Assert that two JSON objects represented as Strings are semantically equal.
 *
 * @param one one./* w w w  .j a v a2  s.  co  m*/
 * @param two two.
 */
public static void assertJsonEquals(String one, String two) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        assertTrue(mapper.readTree(one).equals(mapper.readTree(two)));
    } catch (IOException e) {
        fail();
    }
}

From source file:com.baasbox.configuration.PropertiesConfigurationHelper.java

public static String dumpConfigurationAsJson() {
    ImmutableCollection<String> keys = CONFIGURATION_SECTIONS.keySet();
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory jfactory = mapper.getJsonFactory();
    StringWriter sw = new StringWriter();
    try {/*from   ww  w.j  av  a 2 s  . c om*/
        JsonGenerator gen = jfactory.createJsonGenerator(sw);
        gen.writeStartArray();
        for (String v : keys) {
            String st = dumpConfigurationAsJson(v);
            ObjectMapper op = new ObjectMapper();
            JsonNode p = op.readTree(st);
            BaasBoxLogger.debug("OBJECT:" + p.toString());
            BaasBoxLogger.debug("STRING:" + st);
            //JsonParser jp = jfactory.createJsonParser(st);
            gen.writeTree(p);
        }
        gen.writeEndArray();
        gen.close();
        return sw.toString();
    } catch (Exception e) {
        BaasBoxLogger.error("Cannot generate a json for the configuration", e);
    }
    return "[]";
}

From source file:io.github.robwin.swagger2markup.Swagger2MarkupConverter.java

/**
 * Creates a Swagger2MarkupConverter.Builder from a given Swagger YAML or JSON String.
 *
 * @param swagger the Swagger YAML or JSON String.
 * @return a Swagger2MarkupConverter//from w  w  w  .j  a va2s  .co  m
 * @throws java.io.IOException if String can not be parsed
 */
public static Builder fromString(String swagger) throws IOException {
    Validate.notEmpty(swagger, "swagger must not be null!");
    ObjectMapper mapper;
    if (swagger.trim().startsWith("{")) {
        mapper = Json.mapper();
    } else {
        mapper = Yaml.mapper();
    }
    JsonNode rootNode = mapper.readTree(swagger);

    // must have swagger node set
    JsonNode swaggerNode = rootNode.get("swagger");
    if (swaggerNode == null)
        throw new IllegalArgumentException("Swagger String is in the wrong format");

    return new Builder(mapper.convertValue(rootNode, Swagger.class));
}

From source file:io.orchestrate.client.RelationResource.java

private static JsonNode parseJson(final String json, final ObjectMapper mapper) throws IOException {
    assert (mapper != null);

    try {//www.  j a  va 2 s . c o m
        if (json != null) {
            return mapper.readTree(json);
        }
    } catch (final JsonMappingException ignored) {
    }
    return MissingNode.getInstance();
}

From source file:com.baasbox.service.storage.FileService.java

public static ODocument createFile(String fileName, String dataJson, String aclJsonString, String contentType,
        long length, InputStream is, HashMap<String, Object> extractedMetaData, String extractedContent)
        throws Throwable {
    ODocument doc = createFile(fileName, dataJson, contentType, length, is, extractedMetaData,
            extractedContent);//w  w w  .j av a  2  s.c o  m
    //sets the permissions
    ObjectMapper mapper = new ObjectMapper();
    JsonNode aclJson = null;
    try {
        aclJson = mapper.readTree(aclJsonString);
    } catch (JsonProcessingException e) {
        throw e;
    }
    setAcl(doc, aclJson);
    return doc;
}

From source file:io.orchestrate.client.ResponseConverterUtil.java

@SuppressWarnings("unchecked")
public static <T> KvObject<T> jsonToKvObject(ObjectMapper mapper, String rawValue, Class<T> clazz,
        String collection, String key, String ref) throws IOException {
    assert (mapper != null);
    assert (clazz != null);

    JsonNode valueNode = null;/*from   ww  w  .jav  a  2 s.c o  m*/
    if (rawValue != null && !rawValue.isEmpty()) {
        valueNode = mapper.readTree(rawValue);
    }

    final T value = jsonToDomainObject(mapper, valueNode, rawValue, clazz);

    return new KvObject<T>(collection, key, ref, mapper, value, valueNode, rawValue);
}

From source file:com.mirth.connect.util.MirthJsonUtil.java

public static String prettyPrint(String input) {
    ObjectMapper mapper = new ObjectMapper(new JsonFactory());
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    try {//from   ww w.ja v  a 2  s  .  co  m
        // Modified Jackson's default pretty printer to separate each array element onto its own line
        DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
        prettyPrinter.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
        JsonNode json = mapper.readTree(input);

        return mapper.writer(prettyPrinter).writeValueAsString(json);
    } catch (Exception e) {
        logger.warn("Error pretty printing json.", e);
    }

    return input;
}

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

protected static InputStream getJsonPropertyValue(final InputStream src, final String name) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    final JsonNode srcNode = mapper.readTree(src);
    JsonNode node = getJsonProperty(srcNode, new String[] { name }, 0);
    return IOUtils.toInputStream(node.asText());
}

From source file:com.buzzcoders.yasw.widgets.map.support.GMapUtils.java

/**
 * Returns the coordinates of the specified address.
 * /* w  w  w  .j av  a 2 s  .  c  o  m*/
 * @param addressText the address to look
 * @return the latitude and longitude information
 */
public static LatLng getAddressCoordinates(String addressText) {
    LatLng coordinates = null;
    GetMethod locateAddressGET = null;
    HttpClient client = null;
    try {
        String addressUrlEncoded = URLEncoder.encode(addressText, "UTF-8");
        String locationFindURL = "http://maps.google.com/maps/api/geocode/json?sensor=false&address="
                + addressUrlEncoded;
        client = new HttpClient();
        locateAddressGET = new GetMethod(locationFindURL);
        int httpRetCode = client.executeMethod(locateAddressGET);
        if (httpRetCode == HttpStatus.SC_OK) {
            String responseBodyAsString = locateAddressGET.getResponseBodyAsString();
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            JsonNode jsonRoot = mapper.readTree(responseBodyAsString);
            JsonNode location = jsonRoot.path("results").get(0).path("geometry").path("location");
            JsonNode lat = location.get("lat");
            JsonNode lng = location.get("lng");
            coordinates = new LatLng(lat.asDouble(), lng.asDouble());
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (locateAddressGET != null)
            locateAddressGET.releaseConnection();
        if (client != null)
            client.getState().clear();
    }
    return coordinates;
}