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

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
    public <T> T readValue(byte[] src, JavaType valueType)
            throws IOException, JsonParseException, JsonMappingException 

Source Link

Usage

From source file:com.feedzai.fos.api.ModelConfig.java

/**
 * Reads a model configuration from a file.
 *
 * @param path configuration file path//from w w  w  .  j a va 2s.  c o m
 * @return ModelConfig read from a file
 * @throws FOSException if it wasn't possible to parse a file
 */
public static ModelConfig fromFile(String path) throws FOSException {
    ObjectMapper mapper = new ObjectMapper();
    ModelConfig deserialized;

    try {
        deserialized = mapper.readValue(new File(path), ModelConfig.class);
    } catch (IOException e) {
        throw new FOSException(e.getMessage(), e);
    }

    return deserialized;

}

From source file:io.klerch.alexa.state.utils.ConversionUtils.java

/**
 * A json-string of key-value pairs is read out as a map
 * @param json json-string of key-value pairs
 * @return a map with corresponding key-value paris
 *///from w  ww .  j  ava  2s  .c  o m
public static Map<String, Object> mapJson(final String json) {
    final ObjectMapper mapper = new ObjectMapper();
    if (json == null || json.isEmpty()) {
        return new HashMap<>();
    }
    final TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
    };
    try {
        // read jsonString into map
        return mapper.readValue(json, typeRef);
    } catch (IOException e) {
        log.error(e);
        return new HashMap<>();
    }
}

From source file:de.alpharogroup.xml.json.JsonTransformer.java

/**
 * Transforms the given json string into a java object.
 *
 * @param <T>//from w w w .  j av  a  2s  .  com
 *            the generic type of the return type
 * @param jsonString
 *            the json string
 * @param clazz
 *            the clazz of the generic type
 * @param modules
 *            The modules to register for the mapper
 * @return the object
 * @throws JsonParseException
 *             If an error occurs when parsing the string into Object
 * @throws JsonMappingException
 *             the If an error occurs when mapping the string into Object
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static <T> T toObject(final String jsonString, final Class<T> clazz, final Module... modules)
        throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = getObjectMapper(true);
    mapper = mapper.registerModules(modules);
    final T object = mapper.readValue(jsonString, clazz);
    return object;
}

From source file:cn.org.once.cstack.cli.rest.JsonConverter.java

public static List<EnvironmentVariable> getEnvironmentVariables(String response) {
    List<EnvironmentVariable> environmentVariables = new ArrayList<>();
    ObjectMapper mapper = new ObjectMapper();
    try {//  w  w  w  .  j av  a2s . co  m
        environmentVariables = mapper.readValue(response, new TypeReference<List<EnvironmentVariable>>() {
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
    return environmentVariables;
}

From source file:org.commonjava.maven.firth.client.ArtifactClient.java

public static ArtifactClient load(final String baseUrl, final String mapsBasePath,
        final String packagePathFormat, final String source, final String version) throws IOException {
    final HttpClient http = HttpClientBuilder.create().build();

    // Assume something like: http://download.devel.redhat.com/brewroot/artifact-maps/rcm-mw-tools-build/1234/composition.json
    final String compsUrl = PathUtils.normalize(baseUrl, mapsBasePath, source, version, "composition.json");

    final ObjectMapper om = new ObjectMapper();

    HttpGet request = new HttpGet(compsUrl);
    HttpResponse response = http.execute(request);

    SourceComposition comp;//from  www.  j  av a  2  s  .com
    if (response.getStatusLine().getStatusCode() == 200) {
        comp = om.readValue(response.getEntity().getContent(), SourceComposition.class);
    } else {
        throw new IOException("Failed to read composition from: " + compsUrl);
    }

    final List<String> manifestSources = new ArrayList<String>();
    manifestSources.add(source);
    manifestSources.addAll(comp.getComposedOf());

    final List<SourceManifest> manifests = new ArrayList<SourceManifest>();
    for (final String src : manifestSources) {
        // Assume something like: http://download.devel.redhat.com/brewroot/artifact-maps/rcm-mw-tools-build/1234/manifest.json
        final String manifestUrl = PathUtils.normalize(baseUrl, mapsBasePath, src, version, "manifest.json");
        request = new HttpGet(manifestUrl);
        response = http.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            final SourceManifest manifest = om.readValue(response.getEntity().getContent(),
                    SourceManifest.class);

            manifests.add(manifest);
        } else {
            throw new IOException("Failed to read manifest from: " + manifestUrl);
        }
    }

    final ArtifactMap am = new ArtifactMap(packagePathFormat, manifests);

    return new ArtifactClient(baseUrl, am, http);
}

From source file:com.hotelbeds.distribution.hotel_api_sdk.helpers.LoggingRequestInterceptor.java

public static String writeJSON(final Object object) {
    ObjectMapper mapper = null;
    String result = null;/* w ww  . j a  v a2  s  .c om*/
    mapper = new ObjectMapper();
    try {
        if (object instanceof String) {
            Object json = mapper.readValue((String) object, Object.class);
            result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
        } else {
            result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
        }
    } catch (final IOException e) {
        log.warn("Body is not a json object {}", e.getMessage());
    }
    return result;
}

From source file:cn.org.once.cstack.cli.rest.JsonConverter.java

public static String getCloudUnitInstance(String response) {
    String cloudunitInstance = null;
    ObjectMapper mapper = new ObjectMapper();
    try {/* w  w w  . j  a  v a  2s  .co  m*/
        Map<String, String> map = mapper.readValue(response, new TypeReference<Map<String, String>>() {
        });
        cloudunitInstance = map.get("cuInstanceName");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return cloudunitInstance;
}

From source file:org.killbill.queue.DefaultQueueLifecycle.java

public static <T> T deserializeEvent(final String className, final ObjectMapper objectMapper,
        final String json) {
    try {/*from   w  w  w .  j av  a  2s.  c o m*/
        final Class<?> claz = Class.forName(className);
        return (T) objectMapper.readValue(json, claz);
    } catch (Exception e) {
        log.error(String.format("Failed to deserialize json object %s for class %s", json, className), e);
        return null;
    }
}

From source file:eu.trentorise.opendata.commons.test.jackson.OdtJacksonTester.java

/**
 * Tests that the provided object can be converted to json and
 * reconstructed. Also logs the json with the provided logger at FINE
 * level./*from  w  ww.  j  a  v  a2 s.c  om*/
 *
 * @return the reconstructed object
 */
public static <T> T testJsonConv(ObjectMapper om, Logger logger, @Nullable T obj) {

    checkNotNull(om);
    checkNotNull(logger);

    T recObj;

    try {
        String json = om.writeValueAsString(obj);
        logger.log(Level.FINE, "json = {0}", json);
        Object ret = om.readValue(json, obj.getClass());
        recObj = (T) ret;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

    assertEquals(obj, recObj);
    return recObj;
}

From source file:com.messagehub.samples.bluemix.BluemixEnvironment.java

/**
 * Parses VCAP_SERVICES to extract Message Hub connection configuration
 * @return an instance of MessageHubCredentials
 * @throws IOException on parsing error//  ww w .  jav a 2s. com
 * @throws IllegalStateException if there is no Message Hub service bound to the application
 */
public static MessageHubCredentials getMessageHubCredentials() throws IOException {
    // Arguments parsed via VCAP_SERVICES environment variable.
    String vcapServices = System.getenv("VCAP_SERVICES");
    ObjectMapper mapper = new ObjectMapper();

    try {
        // Parse VCAP_SERVICES into Jackson JsonNode, then map the 'messagehub' entry
        // to an instance of MessageHubEnvironment.
        JsonNode vcapServicesJson = mapper.readValue(vcapServices, JsonNode.class);
        ObjectMapper envMapper = new ObjectMapper();
        String vcapKey = null;
        Iterator<String> it = vcapServicesJson.fieldNames();

        // Find the Message Hub service bound to this application.
        while (it.hasNext() && vcapKey == null) {
            String potentialKey = it.next();

            if (potentialKey.startsWith("messagehub")) {
                logger.log(Level.INFO, "Using the '" + potentialKey + "' key from VCAP_SERVICES.");
                vcapKey = potentialKey;
            }
        }

        // Sanity assertion check
        if (vcapKey == null) {
            logger.log(Level.ERROR,
                    "Error while parsing VCAP_SERVICES: A Message Hub service instance is not bound to this application.");
            throw new IllegalStateException(
                    "Error while parsing VCAP_SERVICES: A Message Hub service instance is not bound to this application.");
        }

        MessageHubEnvironment messageHubEnvironment = envMapper
                .readValue(vcapServicesJson.get(vcapKey).get(0).toString(), MessageHubEnvironment.class);
        MessageHubCredentials credentials = messageHubEnvironment.getCredentials();
        return credentials;
    } catch (IOException e) {
        logger.log(Level.ERROR, "Failed parsing or processing VCAP_SERVICES", e);
        throw e;
    }
}