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:si.mazi.rescu.JSONUtils.java

/**
 * Get a generic map holding the raw data from the JSON string to allow manual type differentiation
 *
 * @param jsonString   The JSON string/*from w w w.j a  v  a  2s . co m*/
 * @param objectMapper The object mapper
 * @return The map
 */
public static Map<String, Object> getJsonGenericMap(String jsonString, ObjectMapper objectMapper) {

    AssertUtil.notNull(jsonString, "jsonString cannot be null");
    AssertUtil.notNull(objectMapper, "objectMapper cannot be null");
    try {
        return objectMapper.readValue(jsonString, new TypeReference<Map<String, Object>>() {
        });
    } catch (IOException e) {
        // Rethrow as runtime exception
        throw new RuntimeException("Problem getting JSON generic map", e);
    }
}

From source file:com.couchbase.client.core.util.ClusterDependentTest.java

private static Integer minNodeVersionFromConfig(String rawConfig) throws Exception {
    ObjectMapper mapper = new ObjectMapper();

    JavaType type = mapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class);
    Map<String, Object> result = mapper.readValue(rawConfig, type);

    List<Object> nodes = (List<Object>) result.get("nodes");
    int min = 99;
    for (Object n : nodes) {
        Map<String, Object> node = (Map<String, Object>) n;
        String version = (String) node.get("version");
        int major = Integer.parseInt(version.substring(0, 1));
        if (major < min) {
            min = major;/*  w ww . j  ava  2  s  .c o m*/
        }
    }
    return min;
}

From source file:gndata.lib.config.AbstractConfig.java

/**
 * Loads a configuration of a certain type from a json file.
 * Note: this method should be used by subclasses in order to implement
 * a more specific load method.//from w  w  w .ja va 2  s  . c  o m
 *
 * @param filePath      Path to the json configuration file to read from.
 * @param cls           The class of the configuration type.
 *
 * @throws IOException
 */
protected static <T extends AbstractConfig> T load(String filePath, Class<T> cls) throws IOException {
    Path tmpPath = Paths.get(filePath);
    ObjectMapper mapper = new ObjectMapper().enable(ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)
            .enable(ACCEPT_SINGLE_VALUE_AS_ARRAY).disable(FAIL_ON_UNKNOWN_PROPERTIES);

    try {
        T config = mapper.readValue(tmpPath.toFile(), cls);
        config.setFilePath(tmpPath.toString());

        return config;
    } catch (IOException e) {
        throw new IOException("Unable to read configuration file: " + filePath, e);
    }
}

From source file:io.github.cdelmas.spike.sparkjava.Main.java

private static void configureUnirest(final ObjectMapper objectMapper) {
    Unirest.setObjectMapper(new com.mashape.unirest.http.ObjectMapper() {
        @Override/*from   w w  w . j  a v  a  2s . co m*/
        public <T> T readValue(String value, Class<T> valueType) {
            try {
                return objectMapper.readValue(value, valueType);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        @Override
        public String writeValue(Object value) {
            try {
                return objectMapper.writeValueAsString(value);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
    });
}

From source file:org.saltyrtc.client.helpers.MessageReader.java

/**
 * Read MessagePack bytes, return a Message subclass instance.
 * @param bytes Messagepack bytes.//  ww w . jav  a2  s  . c  om
 * @param taskTypes List of message types supported by task.
 * @return Message subclass instance.
 * @throws SerializationError Thrown if deserialization fails.
 * @throws ValidationError Thrown if message can be deserialized but is invalid.
 */
public static Message read(byte[] bytes, List<String> taskTypes) throws SerializationError, ValidationError {
    // Unpack data into map
    ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
    Map<String, Object> map;
    try {
        map = objectMapper.readValue(bytes, new TypeReference<Map<String, Object>>() {
        });
    } catch (IOException e) {
        throw new SerializationError("Deserialization failed", e);
    }

    // Get type value
    if (!map.containsKey("type")) {
        throw new SerializationError("Message does not contain a type field");
    }
    Object typeObj = map.get("type");
    if (!(typeObj instanceof String)) {
        throw new SerializationError("Message type must be a string");
    }
    String type = (String) typeObj;

    // Dispatch message instantiation
    switch (type) {
    case "server-hello":
        return new ServerHello(map);
    case "client-hello":
        return new ClientHello(map);
    case "server-auth":
        if (map.containsKey("initiator_connected")) {
            return new ResponderServerAuth(map);
        } else if (map.containsKey("responders")) {
            return new InitiatorServerAuth(map);
        }
        throw new ValidationError("Invalid server-auth message");
    case "client-auth":
        return new ClientAuth(map);
    case "new-initiator":
        return new NewInitiator(map);
    case "new-responder":
        return new NewResponder(map);
    case "drop-responder":
        return new DropResponder(map);
    case "send-error":
        return new SendError(map);
    case "token":
        return new Token(map);
    case "key":
        return new Key(map);
    case "auth":
        if (map.containsKey("task")) {
            return new InitiatorAuth(map);
        } else if (map.containsKey("tasks")) {
            return new ResponderAuth(map);
        }
        throw new ValidationError("Invalid auth message");
    case "close":
        return new Close(map);
    case "application":
        return new Application(map);
    default:
        if (taskTypes.contains(type)) {
            return new TaskMessage(type, map);
        }
        throw new ValidationError("Unknown message type: " + type);
    }
}

From source file:com.twosigma.beakerx.table.serializer.TableDisplayDeSerializer.java

@SuppressWarnings("unchecked")
public static List<String> getClasses(JsonNode n, ObjectMapper mapper) throws IOException {
    List<String> classes = null;
    if (n.has("types"))
        classes = mapper.readValue(n.get("types").toString(), List.class);
    return classes;
}

From source file:com.enremmeta.onenow.Utils.java

public static Config loadConfig(String fileName, Class<? extends Config> configClass)
        throws MalformedURLException, IOException {
    JsonFactory jsonFactory = new JsonFactory();
    jsonFactory.configure(Feature.ALLOW_COMMENTS, true);
    ObjectMapper mapper = new ObjectMapper(jsonFactory);
    Config config;//  w w  w. j  a  v a2 s . c om

    if (fileName.startsWith("http://") || fileName.startsWith("https://")) {
        URL url = new URL(fileName);
        config = mapper.readValue(url, configClass);
    } else {
        File file = new File(fileName);
        config = mapper.readValue(file, configClass);
    }
    return config;
}

From source file:it.uniroma2.sag.kelp.linearization.nystrom.NystromMethodEnsemble.java

/**
 * Load an Ensemble of Nystrom projectors saved on file.
 * /*w  w  w .j  a  v a 2 s  . c o m*/
 * @param inputFilePath
 *            The input file path
 * @return
 * @throws FileNotFoundException
 * @throws IOException
 */
public static NystromMethodEnsemble load(String inputFilePath) throws FileNotFoundException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    InputStream inputStream = FileUtils.createInputStream(inputFilePath);
    return mapper.readValue(inputStream, NystromMethodEnsemble.class);
}

From source file:com.twosigma.beakerx.table.serializer.TableDisplayDeSerializer.java

@SuppressWarnings("unchecked")
public static List<String> getColumns(JsonNode n, ObjectMapper mapper) throws IOException {
    List<String> columns = null;
    if (n.has("columnNames"))
        columns = mapper.readValue(n.get("columnNames").toString(), List.class);
    return columns;
}

From source file:com.liferay.sync.engine.util.SyncClientUpdater.java

public static SyncVersion getLatestSyncVersion() throws Exception {
    HttpResponse httpResponse = execute(PropsValues.SYNC_UPDATE_CHECK_URL);

    if (httpResponse == null) {
        return null;
    }//from w w  w  .  java  2  s. c  o  m

    ObjectMapper objectMapper = new ObjectMapper();

    HttpEntity httpEntity = httpResponse.getEntity();

    return objectMapper.readValue(httpEntity.getContent(), new TypeReference<SyncVersion>() {
    });
}