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

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

Introduction

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

Prototype

public ObjectMapper configure(JsonGenerator.Feature f, boolean state) 

Source Link

Document

Method for changing state of an on/off JsonGenerator feature for JsonFactory instance this object mapper uses.

Usage

From source file:org.terracotta.management.model.cluster.ClusterTest.java

@Test
public void test_toMap() throws IOException {
    String expectedJson = new String(Files.readAllBytes(new File("src/test/resources/cluster.json").toPath()),
            "UTF-8");
    Map actual = cluster1.toMap();
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    assertEquals(expectedJson, mapper.writeValueAsString(actual));
}

From source file:com.xeiam.xchange.mtgox.v2.service.MtGoxAdapterTest.java

@Test
public void testOrderAdapterWithOpenOrders() throws IOException {

    // Read in the JSON from the example resources
    InputStream is = MtGoxAdapterTest.class
            .getResourceAsStream("/v2/trade/polling/example-openorders-data.json");

    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    MtGoxOpenOrder[] mtGoxOpenOrders = mapper.readValue(is, MtGoxOpenOrder[].class);

    List<LimitOrder> openorders = MtGoxAdapters.adaptOrders(mtGoxOpenOrders);
    assertThat(openorders.size()).isEqualTo(38);

    // verify all fields filled
    System.out.println(openorders.get(0).toString());
    assertThat(openorders.get(0).getLimitPrice().getAmount().doubleValue()).isEqualTo(1.25);
    assertThat(openorders.get(0).getType()).isEqualTo(OrderType.BID);
    assertThat(openorders.get(0).getTradableAmount().doubleValue()).isEqualTo(0.23385868);
    assertThat(openorders.get(0).getTradableIdentifier()).isEqualTo("BTC");
    assertThat(openorders.get(0).getTransactionCurrency()).isEqualTo("USD");

    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    f.setTimeZone(TimeZone.getTimeZone("UTC"));
    String dateString = f.format(openorders.get(0).getTimestamp());
    assertThat(dateString).isEqualTo("2012-04-08 14:59:11");
}

From source file:com.xeiam.xchange.mtgox.v2.service.MtGoxAdapterTest.java

@Test
public void testTradeAdapter() throws IOException {

    // Read in the JSON from the example resources
    InputStream is = MtGoxAdapterTest.class
            .getResourceAsStream("/v2/marketdata/polling/example-trades-data.json");

    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    MtGoxTrade[] mtGoxTrades = mapper.readValue(is, MtGoxTrade[].class);

    Trades trades = MtGoxAdapters.adaptTrades(mtGoxTrades);
    assertThat(trades.getTrades().size()).isEqualTo(30);

    // Verify all fields filled
    assertThat(trades.getTrades().get(0).getPrice().getAmount().doubleValue()).isEqualTo(193.99989);
    assertThat(trades.getTrades().get(0).getPrice().getAmount().floatValue()).isEqualTo(193.99989f);
    assertThat(trades.getTrades().get(0).getType()).isEqualTo(OrderType.BID);
    assertThat(trades.getTrades().get(0).getTradableAmount().doubleValue()).isEqualTo(0.01985186);
    assertThat(trades.getTrades().get(0).getTradableIdentifier()).isEqualTo("BTC");
    assertThat(trades.getTrades().get(0).getTransactionCurrency()).isEqualTo("USD");
    assertThat(trades.getTrades().get(0).getId()).isEqualTo(1365499103363494L);
    // Unix 1334177326 = Wed, 11 Apr 2012 20:48:46 GMT
    assertThat(DateUtils.toUTCString(trades.getTrades().get(0).getTimestamp()))
            .isEqualTo("2013-04-09 09:18:23 GMT");
    assertThat(trades.getTrades().get(0).getTimestamp().getTime()).isEqualTo(1365499103363L);
}

From source file:com.xeiam.xchange.mtgox.v2.service.MtGoxAdapterTest.java

@Test
public void testOrderAdapterWithDepth() throws IOException {

    // Read in the JSON from the example resources
    InputStream is = MtGoxAdapterTest.class
            .getResourceAsStream("/v2/marketdata/polling/example-depth-data.json");

    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    MtGoxDepth mtGoxDepth = mapper.readValue(is, MtGoxDepth.class);

    List<LimitOrder> asks = MtGoxAdapters.adaptOrders(mtGoxDepth.getAsks(), "USD", "ask", "id_567");
    System.out.println(asks.size());
    assertThat(asks.size()).isEqualTo(503);

    // Verify all fields filled
    assertThat(asks.get(0).getLimitPrice().getAmount().doubleValue()).isEqualTo(182.99999);
    assertThat(asks.get(0).getType()).isEqualTo(OrderType.ASK);
    assertThat(asks.get(0).getTradableAmount().doubleValue()).isEqualTo(2.46297453);
    assertThat(asks.get(0).getTradableIdentifier()).isEqualTo("BTC");
    assertThat(asks.get(0).getTransactionCurrency()).isEqualTo("USD");

    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    f.setTimeZone(TimeZone.getTimeZone("UTC"));
    String dateString = f.format(asks.get(0).getTimestamp());
    assertThat(dateString).isEqualTo("2013-04-08 18:09:23");

}

From source file:com.nonninz.robomodel.RoboManager.java

public T create(String json) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(MapperFeature.USE_ANNOTATIONS, true);
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    try {/* ww  w  . java  2s .  c om*/
        final T result = mapper.readValue(json, mKlass);
        result.setContext(mContext);
        return result;
    } catch (Exception e) {
        throw new JsonException("Error while parsing JSON", e);
    }
}

From source file:com.nonninz.robomodel.RoboManager.java

public <C extends RoboModelCollection<T>> C createCollection(String json, Class<C> klass) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(MapperFeature.USE_ANNOTATIONS, true);
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    try {/* w  w w .j a v a2  s  .  com*/
        final C result = mapper.readValue(json, klass);
        result.setContext(mContext);
        return result;
    } catch (Exception e) {
        throw new JsonException("Error while parsing JSON", e);
    }
}

From source file:net.sf.gazpachoquest.questionnaires.resource.ResourceProducer.java

@Produces
@GazpachoResource/*from  w w w . j  av a2 s .c  om*/
@RequestScoped
public QuestionnaireResource createQuestionnairResource(HttpServletRequest request) {
    RespondentAccount principal = (RespondentAccount) request.getUserPrincipal();
    String apiKey = principal.getApiKey();
    String secret = principal.getSecret();

    logger.info("Getting QuestionnaireResource using api key {}/{} ", apiKey, secret);

    JacksonJsonProvider jacksonProvider = new JacksonJsonProvider();
    ObjectMapper mapper = new ObjectMapper();
    // mapper.findAndRegisterModules();
    mapper.registerModule(new JSR310Module());
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    jacksonProvider.setMapper(mapper);

    QuestionnaireResource resource = JAXRSClientFactory.create(BASE_URI, QuestionnaireResource.class,
            Collections.singletonList(jacksonProvider), null);
    // proxies
    // WebClient.client(resource).header("Authorization", "GZQ " + apiKey);

    Client client = WebClient.client(resource);
    ClientConfiguration config = WebClient.getConfig(client);
    config.getOutInterceptors().add(new HmacAuthInterceptor(apiKey, secret));
    return resource;
}

From source file:com.linecorp.bot.model.event.CallbackRequestTest.java

private void parse(String resourceName, RequestTester callback) throws IOException {
    try (InputStream resource = getClass().getClassLoader().getResourceAsStream(resourceName)) {
        String json = StreamUtils.copyToString(resource, StandardCharsets.UTF_8);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.registerModule(new JavaTimeModule())
                .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
        CallbackRequest callbackRequest = objectMapper.readValue(json, CallbackRequest.class);

        callback.call(callbackRequest);//from  w w w . java2s  . co m
    }
}

From source file:eu.trentorise.game.repo.GamePersistence.java

public Game toGame() {
    Game game = new Game();
    game.setId(id);/*from   www  . ja  v a2s.  c om*/
    game.setName(name);
    game.setOwner(owner);
    game.setDomain(domain);
    game.setActions(actions);
    game.setRules(rules);
    Set<GameTask> t = new HashSet<GameTask>();
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
    mapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
    for (GenericObjectPersistence obj : tasks) {
        // fix: Use @JsonDeserialize to maintain compatibility with
        // databases previous of version 2.0.0 in which
        // classificationTask was a concrete class representing general
        // classifications
        if (obj.getType().equals(ClassificationTask.class.getCanonicalName())) {
            obj.setType(GeneralClassificationTask.class.getCanonicalName());
        }
        try {
            t.add(mapper.convertValue(obj.getObj(), (Class<? extends GameTask>) Thread.currentThread()
                    .getContextClassLoader().loadClass(obj.getType())));
        } catch (Exception e) {
            LogHub.error(id, logger, "Problem to load class {}", obj.getType(), e);
        }
    }
    game.setTasks(t);

    Set<GameConcept> gc = new HashSet<GameConcept>();
    for (GenericObjectPersistence obj : concepts) {
        try {
            gc.add(mapper.convertValue(obj.getObj(), (Class<? extends GameConcept>) Thread.currentThread()
                    .getContextClassLoader().loadClass(obj.getType())));
        } catch (Exception e) {
            logger.error("Problem to load class {}", obj.getType());
        }
    }
    game.setConcepts(gc);

    if (levels != null) {
        levels.stream().forEach(level -> game.getLevels().add(level));
    }

    game.setExpiration(expiration);
    game.setTerminated(terminated);
    return game;
}

From source file:org.apache.streams.data.MoreoverJsonActivitySerializer.java

@Override
public Activity deserialize(String serialized) {
    serialized = serialized.replaceAll("\\[[ ]*\\]", "null");

    System.out.println(serialized);

    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
    mapper.setAnnotationIntrospector(introspector);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
    mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, Boolean.FALSE);
    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE);
    mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE);
    mapper.configure(DeserializationFeature.WRAP_EXCEPTIONS, Boolean.TRUE);

    Article article;/*from  www . j ava  2s  . c om*/
    try {
        ObjectNode node = (ObjectNode) mapper.readTree(serialized);
        node.remove("tags");
        node.remove("locations");
        node.remove("companies");
        node.remove("topics");
        node.remove("media");
        node.remove("outboundUrls");
        ObjectNode jsonNodes = (ObjectNode) node.get("source").get("feed");
        jsonNodes.remove("editorialTopics");
        jsonNodes.remove("tags");
        jsonNodes.remove("autoTopics");
        article = mapper.convertValue(node, Article.class);
    } catch (IOException e) {
        throw new IllegalArgumentException("Unable to deserialize", e);
    }
    return MoreoverUtils.convert(article);
}