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.twosigma.beakerx.table.serializer.TableDisplayDeSerializer.java

public static Pair<String, Object> getDeserializeObject(BeakerObjectConverter parent, JsonNode n,
        ObjectMapper mapper) {
    Object o = null;/*  ww  w  .  j ava  2 s.  c  o m*/
    String subtype = null;
    try {
        List<List<?>> values = TableDisplayDeSerializer.getValues(parent, n, mapper);
        List<String> columns = TableDisplayDeSerializer.getColumns(n, mapper);
        List<String> classes = TableDisplayDeSerializer.getClasses(n, mapper);

        if (n.has("subtype"))
            subtype = mapper.readValue(n.get("subtype").toString(), String.class);

        if (subtype != null && subtype.equals(TableDisplay.DICTIONARY_SUBTYPE)) {
            o = getValuesAsDictionary(parent, n, mapper);
        } else if (subtype != null && subtype.equals(TableDisplay.LIST_OF_MAPS_SUBTYPE) && columns != null
                && values != null) {
            o = getValuesAsRows(parent, n, mapper);
        } else if (subtype != null && subtype.equals(TableDisplay.MATRIX_SUBTYPE)) {
            o = getValuesAsMatrix(parent, n, mapper);
        }
        if (o == null) {
            if (n.has("hasIndex") && mapper.readValue(n.get("hasIndex").asText(), String.class).equals("true")
                    && columns != null && values != null && n.has(INDEX_NAME)) {
                o = handleIndex(n, mapper, values, columns, classes);
            } else {
                o = new TableDisplay(values, columns, classes);
            }

        }
    } catch (Exception e) {
        logger.error("exception deserializing TableDisplay ", e);
    }
    return new ImmutablePair<String, Object>(subtype, o);
}

From source file:com.hortonworks.streamline.streams.runtime.splitjoin.SplitJoinTest.java

protected static void checkActionWriteReadJsons(Action action) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    final String value = objectMapper.writeValueAsString(action);
    log.info("####### value = " + value);

    Class<? extends Action> actionClass = Action.class;
    Action actionRead = objectMapper.readValue(value, actionClass);
    log.info("####### actionRead = " + actionRead);
}

From source file:com.google.openrtb.json.OpenRtbJsonTest.java

static void testRequestWithNative(String input, String result, boolean rootNative, boolean nativeAsObject,
        boolean ignoreIdField) throws IOException {
    OpenRtbJsonFactory jsonFactory = newJsonFactory().setForceNativeAsObject(nativeAsObject);
    OpenRtb.BidRequest bidRequest = jsonFactory.newReader().readBidRequest(input);
    String jsonRequestNativeStr = jsonFactory.setRootNativeField(rootNative).newWriter()
            .writeBidRequest(bidRequest);
    ObjectMapper mapper = new ObjectMapper();
    Object json = mapper.readValue(jsonRequestNativeStr, Object.class);
    jsonRequestNativeStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);

    if (ignoreIdField) {
        assertThat(cleanupIdField(jsonRequestNativeStr)).isEqualTo(cleanupIdField(result));
    } else {//from  ww  w  .j  a v a  2s  .c om
        assertThat(jsonRequestNativeStr).isEqualTo(result);
    }
}

From source file:com.google.openrtb.json.OpenRtbJsonTest.java

static void testResponseWithNative(String input, String result, boolean rootNative, boolean nativeAsObject,
        boolean ignoreIdField) throws IOException {
    OpenRtbJsonFactory jsonFactory = newJsonFactory().setForceNativeAsObject(nativeAsObject);
    OpenRtb.BidResponse bidResponse1 = jsonFactory.newReader().readBidResponse(input);
    String jsonResponseNativeStr = jsonFactory.setRootNativeField(rootNative).newWriter()
            .writeBidResponse(bidResponse1);
    ObjectMapper mapper = new ObjectMapper();
    Object json = mapper.readValue(jsonResponseNativeStr, Object.class);
    jsonResponseNativeStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);

    if (ignoreIdField) {
        assertThat(cleanupIdField(jsonResponseNativeStr)).isEqualTo(cleanupIdField(result));
    } else {//from   w ww .j a v a 2s . co m
        assertThat(jsonResponseNativeStr).isEqualTo(result);
    }
}

From source file:org.jhk.pulsing.web.service.prod.helper.PulseServiceUtil.java

public static Map<Long, String> processTrendingPulseSubscribe(Set<String> tps, ObjectMapper objMapper) {

    @SuppressWarnings("unchecked")
    Map<Long, String> tpSubscriptions = Collections.EMPTY_MAP;
    final Map<String, Integer> count = new HashMap<>();

    tps.parallelStream().forEach(tpsIdValueCounts -> {

        try {/*  www. ja  va 2s .  c o m*/
            _LOGGER.debug(
                    "PulseServiceUtil.processTrendingPulseSubscribe: trying to convert " + tpsIdValueCounts);

            Map<String, Integer> converted = objMapper.readValue(tpsIdValueCounts,
                    _TRENDING_PULSE_SUBSCRIPTION_TYPE_REF);

            _LOGGER.debug("PulseServiceUtil.processTrendingPulseSubscribe: sucessfully converted "
                    + converted.size());

            //Structure is <id>0x07<value>0x13<timestamp> -> count; i.e. {"10020x07Mocked 10020x13<timestamp>" -> 1}
            //Need to split the String content, gather the count for the searched interval
            //and return the sorted using Java8 stream
            //TODO impl better

            Map<String, Integer> computed = converted.entrySet().stream().reduce(new HashMap<String, Integer>(),
                    (Map<String, Integer> mapped, Entry<String, Integer> entry) -> {
                        String[] split = entry.getKey()
                                .split(CommonConstants.TIME_INTERVAL_PERSIST_TIMESTAMP_DELIM);
                        Integer value = entry.getValue();

                        mapped.compute(split[0], (key, val) -> {
                            return val == null ? value : val + value;
                        });

                        return mapped;
                    }, (Map<String, Integer> result, Map<String, Integer> aggregated) -> {
                        result.putAll(aggregated);
                        return result;
                    });

            computed.entrySet().parallelStream().forEach(entry -> {
                Integer value = entry.getValue();

                count.compute(entry.getKey(), (key, val) -> {
                    return val == null ? value : val + value;
                });
            });

        } catch (Exception cException) {
            cException.printStackTrace();
        }
    });

    if (count.size() > 0) {
        tpSubscriptions = count.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .collect(Collectors.toMap(
                        entry -> Long.parseLong(
                                entry.getKey().split(CommonConstants.TIME_INTERVAL_ID_VALUE_DELIM)[0]),
                        entry -> entry.getKey().split(CommonConstants.TIME_INTERVAL_ID_VALUE_DELIM)[1],
                        (x, y) -> {
                            throw new AssertionError();
                        }, LinkedHashMap::new));
    }

    return tpSubscriptions;
}

From source file:org.fastj.fit.tool.JSONHelper.java

public static Map<String, Object> getJson(String content) {
    if (content == null || (content = content.trim()).isEmpty()) {
        return new HashMap<String, Object>();
    }//www. j av a2 s  .c  o m
    Map<String, Object> jo = null;
    if (content.matches("^(\\{|\\[)[\\S\\s]*(\\}|\\])$")) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            if (content.startsWith("{")) {
                jo = mapper.readValue(content, new JsonType<Map<String, Object>>());
            } else {
                Object l = mapper.readValue(content, new JsonType<List<Object>>());
                jo = new HashMap<>();
                jo.put("list", l);
            }
        } catch (Throwable e) {
        }
    }

    //xml
    if (jo == null) {
        if (content.matches("^<[\\S\\s]*>$")) {
            Document doc = JdomHelper.build(content);
            if (doc != null) {
                jo = xml2Json(doc);
            }
        }

        if (jo == null) {
            jo = new HashMap<String, Object>();
            jo.put("content", content);
        }
    }

    return jo;
}

From source file:de.stadtrallye.rallyesoft.model.Server.java

public static void load() {
    try {//w w w  . j  av a  2  s  .c  o m
        ObjectMapper mapper = Serialization.getJsonInstance();

        currentServer = mapper.readValue(Storage.getServerConfigInputStream(), Server.class);
    } catch (FileNotFoundException e) {
        Log.w(THIS, "No previously saved Server!");
    } catch (IOException e) {
        Log.e(THIS, "Cannot load Server", e);
    }
    //      notifyCurrentServerChanged();
}

From source file:org.apache.drill.test.framework.Utils.java

private static TestCaseModeler getTestCaseModeler(String testDefFile) throws IOException {
    byte[] jsonData = Files.readAllBytes(Paths.get(testDefFile));
    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.readValue(new String(jsonData), TestCaseModeler.class);
}

From source file:de.stadtrallye.rallyesoft.model.Server.java

public static Server load(String json) {
    if (json == null)
        return null;

    ObjectMapper mapper = Serialization.getJsonInstance();
    try {//from  w ww .  j av a 2s.c  o m
        return mapper.readValue(json, Server.class);
    } catch (IOException e) {
        Log.e(THIS, "Failed to deserialize Server", e);
        return null;
    }
}

From source file:com.dssmp.agent.config.Configuration.java

/**
 * Build a configuration from an input stream containing JSON.
 *
 * @param is//  ww w  .  jav  a2  s. c o  m
 * @return
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public static Configuration get(InputStream is) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    return new Configuration(
            (Map<String, Object>) mapper.readValue(is, new TypeReference<HashMap<String, Object>>() {
            }));
}