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

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public <T> T readValue(JsonNode src) throws IOException, JsonProcessingException 

Source Link

Document

Convenience method for converting results from given JSON tree into given value type.

Usage

From source file:com.basistech.rosette.dm.json.plain.JsonTest.java

@Test
public void roundTrip() throws Exception {
    StringWriter writer = new StringWriter();
    ObjectMapper mapper = AnnotatedDataModelModule.setupObjectMapper(new ObjectMapper());
    ObjectWriter objectWriter = mapper.writer();
    objectWriter.writeValue(writer, referenceText);

    ObjectReader reader = mapper.readerFor(AnnotatedText.class);
    AnnotatedText read = reader.readValue(writer.toString());

    ListAttribute<BaseNounPhrase> bnpList = read.getBaseNounPhrases();
    assertNotNull(bnpList);//from   w  ww.  j  av a2  s  .c  o  m
    assertEquals(1, bnpList.size());
    BaseNounPhrase bnp = bnpList.get(0);
    assertEquals(baseNounPhrase, bnp);

    ListAttribute<Entity> entityList = read.getEntities();
    assertNotNull(entityList);
    assertEquals(1, entityList.size());
    Entity en = entityList.get(0);
    assertEquals(0.4, en.getSalience(), 0.0001); // just make sure the salience field works all around.
    assertEquals(entity, en);

    ListAttribute<RelationshipMention> rmList = read.getRelationshipMentions();
    assertNotNull(rmList);
    assertEquals(1, rmList.size());
    RelationshipMention rm = rmList.get(0);
    assertEquals(relationshipMention, rm);

    ListAttribute<LanguageDetection> languageDetectionList = read.getLanguageDetectionRegions();
    assertNotNull(languageDetectionList);
    assertEquals(1, languageDetectionList.size());

    assertEquals(languageDetectionRegion, languageDetectionList.get(0));
    assertEquals(languageDetection, read.getWholeTextLanguageDetection());

    ListAttribute<ScriptRegion> scriptRegionList = read.getScriptRegions();
    assertNotNull(scriptRegionList);
    assertEquals(1, scriptRegionList.size());

    assertEquals(scriptRegion, scriptRegionList.get(0));

    ListAttribute<Sentence> sentences = read.getSentences();
    assertNotNull(sentences);

    assertEquals(sentence, sentences.get(0));

    ListAttribute<Token> tokenList = read.getTokens();
    assertNotNull(tokenList);
    assertEquals(1, tokenList.size());
    assertEquals(token, tokenList.get(0));

    ListAttribute<TranslatedData> dataTranslations = read.getTranslatedData();
    assertEquals(germanTranslatedData, dataTranslations.get(0));
    assertEquals(spanishTranslatedData, dataTranslations.get(1));

    ListAttribute<TranslatedTokens> translatedTokens = read.getTranslatedTokens();
    assertEquals(germanTranslation, translatedTokens.get(0));
    assertEquals(spanishTranslation, translatedTokens.get(1));

    assertEquals(categoryResult, read.getCategorizerResults().get(0));

    assertEquals(sentimentResult, read.getSentimentResults().get(0));

    assertEquals("V", read.getDependencies().get(0).getRelationship());
    assertEquals(-1, read.getDependencies().get(0).getGovernorTokenIndex());
    assertEquals(0, read.getDependencies().get(0).getDependencyTokenIndex());

    assertEquals(topicResult, read.getTopicResults().get(0));

    Embeddings readEmbeddings = read.getEmbeddings();
    assertEquals(embeddings, readEmbeddings);
}

From source file:org.apereo.portal.events.aggr.JpaStatisticalSummaryTest.java

public void testStorelessUnivariateStatistic(StorelessUnivariateStatistic sus, double expected)
        throws Exception {

    assertEquals(expected, sus.getResult(), 0.1);

    final ObjectMapper mapper = new ObjectMapper();
    mapper.findAndRegisterModules();// ww w.ja v  a 2 s. c o m

    //Configure Jackson to just use fields
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.SETTER, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.CREATOR, Visibility.NONE);

    mapper.addMixInAnnotations(Object.class, IgnoreTypeMixIn.class);

    final FilterProvider filters = new SimpleFilterProvider().addFilter("storedDataFilter",
            SimpleBeanPropertyFilter.serializeAllExcept("storedData"));

    final ObjectWriter ssWriter = mapper.writer(filters);
    final ObjectReader ssReader = mapper.reader(sus.getClass());

    final String susString = ssWriter.writeValueAsString(sus);
    System.out.println(susString);
    final StorelessUnivariateStatistic newSus = ssReader.readValue(susString);

    assertEquals(expected, newSus.getResult(), 0.1);
}

From source file:org.lenskit.data.entities.EntityDefaults.java

/**
 * Look up the defaults for a particular entity type.
 * @param type The entity type.//w  w  w.j  a v  a  2  s  .  c om
 * @return The defaults.
 */
@Nullable
public static EntityDefaults lookup(EntityType type) {
    // TODO Cache these defaults
    String name = type.getName();
    String path = String.format("META-INF/lenskit/entity-defaults/%s.yaml", name);
    try (InputStream stream = ClassLoaders.inferDefault(EntityDefaults.class).getResourceAsStream(path)) {
        if (stream == null) {
            return null;
        }
        ObjectReader read = new ObjectMapper(new YAMLFactory()).readerFor(DefaultsBean.class);
        DefaultsBean bean = read.readValue(stream);
        return fromBean(type, bean);
    } catch (IOException e) {
        throw new RuntimeException("error reading defaults", e);
    }
}

From source file:org.lenskit.specs.SpecUtils.java

/**
 * Read a specification type from a file.
 * @param type The specification type./*from w w  w .j av  a2s  .  c o  m*/
 * @param file The file to read from.
 * @param <T> The specification type.
 * @return A deserialized specification.
 * @throws IOException if there is an error reading the file.
 */
public static <T> T load(Class<T> type, Path file) throws IOException {
    ObjectReader reader = createMapper().reader(type);
    return reader.readValue(file.toFile());
}

From source file:org.lenskit.specs.SpecUtils.java

/**
 * Read a list of specifications from a file.
 * @param type The specification type.//from  www .jav a  2s.  com
 * @param file The file to read from.
 * @param <T> The specification type.
 * @return A deserialized specification.
 * @throws IOException if there is an error reading the file.
 */
public static <T> List<T> loadList(Class<T> type, Path file) throws IOException {
    ObjectMapper mapper = createMapper();
    JavaType listType = mapper.getTypeFactory().constructCollectionType(List.class, type);
    ObjectReader reader = createMapper().reader(listType);
    return reader.readValue(file.toFile());
}

From source file:org.lenskit.specs.SpecUtils.java

/**
 * Parse a specification from a string./*  w  w  w . j a va  2  s  . com*/
 * @param type The specification type.
 * @param json A string of JSON data.
 * @param <T> The specification type.
 * @return A deserialized specification.
 */
public static <T> T parse(Class<T> type, String json) {
    ObjectReader reader = createMapper().reader(type);
    try {
        return reader.readValue(json);
    } catch (IOException e) {
        throw new RuntimeException("error parsing JSON specification", e);
    }
}

From source file:org.opencb.cellbase.client.rest.ParentRestClient.java

private static <U> QueryResponse<U> parseResult(String json, Class<U> clazz) throws IOException {
    ObjectReader reader = jsonObjectMapper.readerFor(jsonObjectMapper.getTypeFactory()
            .constructParametrizedType(QueryResponse.class, QueryResult.class, clazz));
    return reader.readValue(json);
}

From source file:org.tinymediamanager.core.movie.MovieList.java

/**
 * Load movies from database.//from   w w w .  j  a  v a2  s . c  o  m
 */
void loadMoviesFromDatabase(MVMap<UUID, String> movieMap, ObjectMapper objectMapper) {
    // load movies
    movieList = new ObservableElementList<>(GlazedLists.threadSafeList(new BasicEventList<Movie>()),
            GlazedLists.beanConnector(Movie.class));
    ObjectReader movieObjectReader = objectMapper.readerFor(Movie.class);

    for (UUID uuid : movieMap.keyList()) {
        String json = "";
        try {
            json = movieMap.get(uuid);
            Movie movie = movieObjectReader.readValue(json);
            movie.setDbId(uuid);
            // for performance reasons we add movies directly
            movieList.add(movie);
        } catch (Exception e) {
            LOGGER.warn("problem decoding movie json string: ", e);
        }
    }
    LOGGER.info("found " + movieList.size() + " movies in database");
}

From source file:org.tinymediamanager.core.movie.MovieList.java

void loadMovieSetsFromDatabase(MVMap<UUID, String> movieSetMap, ObjectMapper objectMapper) {
    // load movie sets
    movieSetList = ObservableCollections
            .observableList(Collections.synchronizedList(new ArrayList<MovieSet>()));
    ObjectReader movieSetObjectReader = objectMapper.readerFor(MovieSet.class);

    for (UUID uuid : movieSetMap.keyList()) {
        try {/*from   ww  w  .j  ava  2 s.  co  m*/
            MovieSet movieSet = movieSetObjectReader.readValue(movieSetMap.get(uuid));
            movieSet.setDbId(uuid);
            // for performance reasons we add movies sets directly
            movieSetList.add(movieSet);
        } catch (Exception e) {
            LOGGER.warn("problem decoding movie set json string: ", e);
        }
    }

    LOGGER.info("found " + movieSetList.size() + " movieSets in database");
}