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:org.apache.ode.jacob.examples.helloworld.HelloWorld.java

public static JacksonExecutionQueueImpl loadAndRestoreQueue(ObjectMapper mapper, JacksonExecutionQueueImpl in)
        throws Exception {
    byte[] json = mapper.writeValueAsBytes(in);
    // print json
    // System.out.println(new String(json));
    JacksonExecutionQueueImpl q2 = mapper.readValue(json, JacksonExecutionQueueImpl.class);
    return q2;//from w  w  w  .jav  a2 s  .c  om
}

From source file:io.github.retz.mesosc.MesosHTTPFetcher.java

public static List<Map<String, Object>> parseTasks(InputStream in, String frameworkId) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    List<Map<String, Object>> ret = new ArrayList<>();

    Map<String, List<Map<String, Object>>> map = mapper.readValue(in, Map.class);
    List<Map<String, Object>> tasks = map.get("tasks");
    for (Map<String, Object> task : tasks) {
        String fid = (String) task.get("framework_id");
        if (!frameworkId.equals(fid)) {
            continue;
        }/* w ww .j  a va2s .  c  o m*/
        ret.add(task);
    }
    return ret;
}

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

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

    checkNotNull(om);
    checkNotNull(logger);

    T recObj;

    String json;

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

    assertEquals(obj, recObj);
    return recObj;
}

From source file:plugins.marauders.MaraudersInteractor.java

public static Data getData() {
    StringBuilder json = new StringBuilder();
    try {/*from  www.ja  va 2s.  c om*/
        URL server = new URL("http://s40server.csse.rose-hulman.edu:9200/marauders/data/0");
        URLConnection yc = server.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null && inputLine != "") {
            System.out.println(inputLine);
            json.append(inputLine);
        }

        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    ObjectMapper mapper = new ObjectMapper();
    TypeReference<HashMap<String, Object>> typeReference = new TypeReference<HashMap<String, Object>>() {
    };
    try {
        HashMap<String, Object> map = mapper.readValue(json.toString(), typeReference);
        HashMap<String, Object> source = (HashMap) map.get("_source");
        Data d = new Data();
        d.setLastStudentID(Integer.parseInt((String) source.get("lastStudentID")));
        d.setMaxInsultID(Integer.parseInt((String) source.get("maxInsultID")));
        d.setPassphrase((String) source.get("passphrase"));
        return d;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

}

From source file:org.hawkular.bus.common.AbstractMessage.java

/**
 * Convenience static method that reads a JSON string from the given stream and converts the JSON
 * string to a particular message object. The input stream will remain open so the caller can
 * stream any extra data that might appear after it.
 *
 * Because of the way the JSON parser works, some extra data might have been read from the stream
 * that wasn't part of the JSON message but was part of the extra data that came with it. Because of this,
 * the caller should no longer use the given stream but instead read the extra data via the returned
 * object (see {@link BasicMessageWithExtraData#getBinaryData()}) since it will handle this condition
 * properly./*  w w w  .j  a  v  a  2 s .  c  o m*/
 *
 * @param in input stream that has a JSON string at the head.
 * @param clazz the class whose instance is represented by the JSON string
 *
 * @return a POJO that contains a message object that was represented by the JSON string found
 *         in the stream. This returned POJO will also contain a {@link BinaryData} object that you
 *         can use to stream any additional data that came in the given input stream.
 */
public static <T extends BasicMessage> BasicMessageWithExtraData<T> fromJSON(InputStream in, Class<T> clazz) {
    final T obj;
    final byte[] remainder;
    try (JsonParser parser = new JsonFactory().configure(Feature.AUTO_CLOSE_SOURCE, false).createParser(in)) {
        Method buildObjectMapperForDeserializationMethod = findBuildObjectMapperForDeserializationMethod(clazz);

        final ObjectMapper mapper = (ObjectMapper) buildObjectMapperForDeserializationMethod.invoke(null);
        if (FailOnUnknownProperties.class.isAssignableFrom(clazz)) {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
        }

        obj = mapper.readValue(parser, clazz);
        final ByteArrayOutputStream remainderStream = new ByteArrayOutputStream();
        final int released = parser.releaseBuffered(remainderStream);
        remainder = (released > 0) ? remainderStream.toByteArray() : new byte[0];
    } catch (Exception e) {
        throw new IllegalArgumentException("Stream cannot be converted to JSON object of type [" + clazz + "]",
                e);
    }
    return new BasicMessageWithExtraData<T>(obj, new BinaryData(remainder, in));
}

From source file:com.spotify.helios.common.descriptors.JobTest.java

private static void removeFieldAndParse(final Job job, final String... fieldNames) throws Exception {
    final String jobJson = job.toJsonString();

    final ObjectMapper objectMapper = new ObjectMapper();
    final Map<String, Object> fields = objectMapper.readValue(jobJson,
            new TypeReference<Map<String, Object>>() {
            });/*from  ww w. j  av  a  2s .  c o  m*/

    for (final String field : fieldNames) {
        fields.remove(field);
    }
    final String modifiedJobJson = objectMapper.writeValueAsString(fields);

    final Job parsedJob = parse(modifiedJobJson, Job.class);

    assertEquals(job, parsedJob);
}

From source file:de.undercouch.actson.JsonParserTest.java

/**
 * Assert that two JSON arrays are equal
 * @param expected the expected JSON array
 * @param actual the actual JSON array/*  ww w .  ja v  a 2s.  c o  m*/
 */
private static void assertJsonArrayEquals(String expected, String actual) {
    ObjectMapper mapper = new ObjectMapper();
    TypeReference<List<Object>> ref = new TypeReference<List<Object>>() {
    };
    try {
        List<Object> el = mapper.readValue(expected, ref);
        List<Object> al = mapper.readValue(actual, ref);
        assertEquals(el, al);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:eu.europa.ec.fisheries.uvms.spatial.service.util.MapConfigHelper.java

public static VisibilitySettingsDto getVisibilitySettings(String visibilitySettings) throws ServiceException {
    if (visibilitySettings == null) {
        return null;
    }/*from w w  w  .j a v  a 2 s.  com*/
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        return mapper.readValue(visibilitySettings, VisibilitySettingsDto.class);
    } catch (IOException e) {
        throw new ServiceException("Parse Exception from Json to Object", e);
    }
}

From source file:eu.europa.ec.fisheries.uvms.spatial.service.util.MapConfigHelper.java

public static StyleSettingsDto getStyleSettings(String styleSettings) throws ServiceException {
    if (styleSettings == null) {
        return null;
    }/*  w ww .j a v  a  2s.  c  om*/
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        return mapper.readValue(styleSettings, StyleSettingsDto.class);
    } catch (IOException e) {
        throw new ServiceException("Parse Exception from Json to Object", e);
    }
}

From source file:org.helm.notation2.Nucleotide.java

public static Nucleotide fromJSON(String json) {
    ObjectMapper mapper = new ObjectMapper();

    try {/* w  w w  . ja  v a2 s . c  om*/
        Nucleotide nuc = mapper.readValue(json, Nucleotide.class);
        return nuc;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}