Example usage for com.fasterxml.jackson.core.type TypeReference TypeReference

List of usage examples for com.fasterxml.jackson.core.type TypeReference TypeReference

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core.type TypeReference TypeReference.

Prototype

protected TypeReference() 

Source Link

Usage

From source file:com.xeiam.xchange.mtgox.v1.service.marketdata.streaming.TradeJSONTest.java

@Test
public void testStreamingUnmarshal() throws IOException {

    // Read in the JSON from the example resources
    InputStream is = TradeJSONTest.class
            .getResourceAsStream("/v1/marketdata/streaming/example-trade-streaming-data.json");

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    Map<String, Object> userInMap = mapper.readValue(is, new TypeReference<Map<String, Object>>() {
    });// w  w w  . ja  va  2  s . c  om

    MtGoxTrade mtGoxTrade = mapper.readValue(mapper.writeValueAsString(userInMap.get("trade")),
            MtGoxTrade.class);

    // Verify that the example data was unmarshalled correctly
    assertThat(mtGoxTrade.getPriceInt()).isEqualTo(9079995L);
    assertThat(mtGoxTrade.getAmountInt()).isEqualTo(1851242L);
    assertThat(mtGoxTrade.getTid()).isEqualTo(1364652424875559L);

}

From source file:org.mayocat.shop.catalog.store.jdbi.mapper.ProductMapper.java

@Override
public Product map(int index, ResultSet resultSet, StatementContext statementContext) throws SQLException {
    try {/*from w  w w  .j  a  va 2s .  c  om*/
        Product product = new Product((UUID) resultSet.getObject("id"));
        product.setTenantId((UUID) resultSet.getObject("tenant_id"));
        if (resultSet.getObject("parent_id") != null) {
            product.setParentId((UUID) resultSet.getObject("parent_id"));
        }
        product.setSlug(resultSet.getString("slug"));
        product.setTitle(resultSet.getString("title"));
        product.setDescription(resultSet.getString("description"));
        product.setCreationDate(resultSet.getTimestamp("creation_date"));
        if (resultSet.getObject("on_shelf") != null) {
            product.setOnShelf(resultSet.getBoolean("on_shelf"));
        }
        product.setPrice(resultSet.getBigDecimal("price"));

        if (!Strings.isNullOrEmpty(resultSet.getString("taxes"))) {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, String> taxes = mapper.readValue(resultSet.getString("taxes"),
                    new TypeReference<Map<String, String>>() {
                    });
            if (taxes.containsKey("vat")) {
                product.setVatRateId(taxes.get("vat"));
            }
        }

        product.setWeight(resultSet.getBigDecimal("weight"));
        if (resultSet.getObject("stock") != null) {
            product.setStock(resultSet.getInt("stock"));
        }
        product.setVirtual(resultSet.getBoolean("virtual"));
        UUID featuredImageId = (UUID) resultSet.getObject("featured_image_id");
        if (featuredImageId != null) {
            product.setFeaturedImageId(featuredImageId);
        }

        if (MapperUtils.hasColumn("localization_data", resultSet)
                && !Strings.isNullOrEmpty(resultSet.getString("localization_data"))) {
            ObjectMapper mapper = new ObjectMapper();
            Map<Locale, Map<String, Object>> localizedVersions = Maps.newHashMap();
            Map[] data = mapper.readValue(resultSet.getString("localization_data"), Map[].class);
            for (Map map : data) {

                localizedVersions.put(Locale.forLanguageTag((String) map.get("locale")),
                        (Map) map.get("entity"));
            }
            product.setLocalizedVersions(localizedVersions);
        }

        String model = resultSet.getString("model");
        if (!Strings.isNullOrEmpty(model)) {
            product.setModel(model);
        }
        String type = resultSet.getString("product_type");
        if (!Strings.isNullOrEmpty(type)) {
            product.setType(type);
        }

        if (resultSet.getArray("features") != null) {
            // There's no support for getting the pg uuid array as a Java UUID array (or even String array) at the time
            // this is written, we have to iterate over the array own result set and construct the Java array ourselves
            List<UUID> ids = new ArrayList<>();
            Array array = resultSet.getArray("features");
            if (array != null) {
                ResultSet featuresResultSet = array.getResultSet();
                while (featuresResultSet.next()) {
                    ids.add((UUID) featuresResultSet.getObject("value"));
                }
                product.setFeatures(ids);
            }
        }

        return product;
    } catch (IOException e) {
        throw new SQLException("Failed to de-serialize JSON data", e);
    }
}

From source file:com.yahoo.druid.pig.udfs.PostAggregatorAdapter.java

public PostAggregatorAdapter(String aggFactorySpec, String inputSchema) {
    ObjectMapper jsonMapper = HadoopDruidIndexerConfig.jsonMapper;
    try {//from w  w w. j  ava 2s  .  c o m
        this.aggFactory = jsonMapper.readValue(aggFactorySpec, PostAggregator.class);
        this.columnTypes = jsonMapper.readValue(inputSchema, new TypeReference<List<Metric>>() {
        });
    } catch (IOException ex) {
        throw new IllegalArgumentException("failed to create aggregator factory", ex);
    }
}

From source file:net.mostlyharmless.jghservice.connector.github.GetCommentsOnIssue.java

@Override
public List<GithubEvent.Comment> processResponse(String jsonResponse) throws IOException {
    TypeReference<List<GithubEvent.Comment>> tr = new TypeReference<List<GithubEvent.Comment>>() {
    };/*w w w  .ja  va2s  . com*/
    ObjectMapper m = new ObjectMapperProvider().getContext(GithubEvent.Comment.class);
    return m.readValue(jsonResponse, tr);
}

From source file:com.netflix.suro.sink.localfile.TestTextFileWriter.java

@Test
public void test() throws IOException {
    String dir = tempDir.newFolder().getAbsolutePath();

    String spec = "{\n" + "    \"type\": \"text\"\n" + "}";
    ObjectMapper mapper = injector.getInstance(ObjectMapper.class);
    FileWriter writer = mapper.readValue(spec, new TypeReference<FileWriter>() {
    });/*from  ww  w . j a v  a2s . com*/
    writer.open(dir);

    assertEquals(writer.getLength(), 0);
    writer.rotate(dir + "testfile0.suro");
    for (int i = 0; i < 10; ++i) {
        writer.writeTo(new Message("routingKey", ("message0" + i).getBytes()));
    }
    System.out.println("length: " + writer.getLength());
    assertEquals(writer.getLength(), 100);

    writer.rotate(dir + "testfile1.suro");
    assertEquals(writer.getLength(), 0);
    assertEquals(checkFileContents(dir + "testfile0.suro", "message0"), 10);

    writer.setDone(dir + "testfile0.suro", dir + "testfile0.done");
    assertFalse(new File(dir + "testfile0.suro").exists());
    checkFileContents(dir + "testfile0.done", "message0");

    for (int i = 0; i < 10; ++i) {
        writer.writeTo(new Message("routingKey", ("message1" + i).getBytes()));
    }
    writer.close();
    assertEquals(checkFileContents(dir + "testfile1.suro", "message1"), 10);
}

From source file:io.fouad.jtb.core.beans.BooleanOrMessageResult.java

public BooleanOrMessageResult(String result) throws IOException {
    if (result != null) {
        if (result.equalsIgnoreCase("true"))
            this.booleanResult = true;
        else if (result.equalsIgnoreCase("false"))
            this.booleanResult = false;
        else {//from w w w.j a v  a  2 s  . c o m
            TelegramResult<Message> telegramResult = JsonUtils.toJavaObject(result,
                    new TypeReference<TelegramResult<Message>>() {
                    });
            this.messageResult = telegramResult.getResult();
        }
    }
}

From source file:com.xeiam.xchange.mtgox.v1.service.marketdata.streaming.DepthUpdateJSONTest.java

@Test
public void testStreamingUnmarshal() throws IOException {

    // Read in the JSON from the example resources
    InputStream is = DepthUpdateJSONTest.class
            .getResourceAsStream("/v1/marketdata/streaming/example-depth-streaming-data.json");

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    Map<String, Object> userInMap = mapper.readValue(is, new TypeReference<Map<String, Object>>() {
    });/*from   www.j av  a2  s . c  om*/

    MtGoxDepthUpdate mtGoxDepthUpdate = mapper.readValue(mapper.writeValueAsString(userInMap.get("depth")),
            MtGoxDepthUpdate.class);

    // Verify that the example data was unmarshalled correctly
    assertThat(mtGoxDepthUpdate.getPriceInt()).isEqualTo(6250000L);
    assertThat(mtGoxDepthUpdate.getCurrency()).isEqualTo("USD");

}

From source file:com.evrythng.java.wrapper.util.JSONUtilsTest.java

@Test
public void deserializeLess() {

    String json = "{\"myProp\":\"1\" }";

    MyObject o = JSONUtils.read(json, new TypeReference<MyObject>() {
    });/*from   w  ww . jav a2  s . c  o  m*/

    Assert.assertEquals("1", o.getMyProp());
    Assert.assertNull(o.getB());
    Assert.assertNull(o.getSub());
}

From source file:com.networknt.light.rule.user.SignUpUserRuleTest.java

public void testExecute() throws Exception {
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    boolean ruleResult = false;
    try {// w  w  w  .  ja va 2s.  c o m
        // signUp user no error
        {
            jsonMap = mapper.readValue(signUp, new TypeReference<HashMap<String, Object>>() {
            });

            SignUpUserRule rule = new SignUpUserRule();
            ruleResult = rule.execute(jsonMap);
            assertTrue(ruleResult);
            Map<String, Object> eventMap = (Map<String, Object>) jsonMap.get("eventMap");
            Map<String, Object> data = (Map<String, Object>) eventMap.get("data");
            String password = (String) data.get("password");
            assertFalse("abcdefg".equals(password));
            SignUpUserEvRule evRule = new SignUpUserEvRule();
            ruleResult = evRule.execute(eventMap);
            assertTrue(ruleResult);
        }
        // signUp user with error
        {
            jsonMap = mapper.readValue(signUpJsonPasswordDiff, new TypeReference<HashMap<String, Object>>() {
            });

            SignUpUserRule rule = new SignUpUserRule();
            ruleResult = rule.execute(jsonMap);
            assertFalse(ruleResult);
            String error = (String) jsonMap.get("error");
            assertEquals("password and password confirm are not the same", error);
            int responseCode = (int) jsonMap.get("responseCode");
            assertEquals(400, responseCode);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}