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:com.xeiam.xchange.mtgox.v1.service.marketdata.TickerJSONTest.java

@Test
public void testStreamingUnmarshal() throws IOException {

    // Read in the JSON from the example resources
    InputStream is = TickerJSONTest.class.getResourceAsStream("/marketdata/example-ticker-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  ww . j a v a  2 s  . c  o m
    // System.out.println(userInMap.get("ticker").toString());
    // System.out.println(mapper.writeValueAsString(userInMap.get("ticker")));

    // Use Jackson to parse it
    mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    MtGoxTicker mtGoxTicker = mapper.readValue(mapper.writeValueAsString(userInMap.get("ticker")),
            MtGoxTicker.class);

    // Verify that the example data was unmarshalled correctly
    assertThat("Unexpected Return Buy value", mtGoxTicker.getBuy().getValue().doubleValue(), equalTo(5.10991));
    assertThat("Unexpected Return Last value", mtGoxTicker.getLast().getValue().doubleValue(),
            equalTo(5.10991));
    assertThat("Unexpected Return Bid value", mtGoxTicker.getBuy().getValue().doubleValue(), equalTo(5.10991));
    assertThat("Unexpected Return Ask value", mtGoxTicker.getSell().getValue().doubleValue(), equalTo(5.11000));
    assertThat("Unexpected Return High value", mtGoxTicker.getHigh().getValue().doubleValue(),
            equalTo(5.12500));
    assertThat("Unexpected Return Low value", mtGoxTicker.getLow().getValue().doubleValue(), equalTo(5.07000));
    assertThat("Unexpected Return Volume value", mtGoxTicker.getVol().getValue().doubleValue(),
            equalTo(15475.00497509));

}

From source file:org.terracotta.management.registry.ManagementRegistryTest.java

@Test
public void test_management_registry_exposes() throws IOException {
    ManagementRegistry registry = new AbstractManagementRegistry() {
        @Override/* ww w . j a  v a 2  s  . c o  m*/
        public ContextContainer getContextContainer() {
            return new ContextContainer("cacheManagerName", "my-cm-name");
        }
    };

    registry.addManagementProvider(new MyManagementProvider());

    registry.register(new MyObject("myCacheManagerName", "myCacheName1"));
    registry.register(new MyObject("myCacheManagerName", "myCacheName2"));

    Scanner scanner = new Scanner(ManagementRegistryTest.class.getResourceAsStream("/capabilities.json"),
            "UTF-8").useDelimiter("\\A");
    String expectedJson = scanner.next();
    scanner.close();

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    mapper.addMixIn(CapabilityContext.class, CapabilityContextMixin.class);

    String actual = mapper.writeValueAsString(registry.getCapabilities());
    System.out.println(expectedJson);
    System.out.println(actual);
    assertEquals(expectedJson, actual);

    ContextualReturn<?> cr = registry.withCapability("TheActionProvider")
            .call("incr", int.class, new Parameter(Integer.MAX_VALUE, "int")).on(Context.empty()
                    .with("cacheManagerName", "myCacheManagerName").with("cacheName", "myCacheName1"))
            .build().execute().getSingleResult();

    try {
        cr.getValue();
        fail();
    } catch (ExecutionException e) {
        assertEquals(IllegalArgumentException.class, e.getCause().getClass());
    }
}

From source file:org.moserp.common.json_schema.ObjectMapperBuilder.java

public ObjectMapper build() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
    mapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    registerQuantitySerializer(mapper);//from  w ww.  j  a  va2  s .c  om
    mapper.registerModules(new MoneyModule(), new JavaTimeModule(), new Jackson2HalModule());

    return mapper;
}

From source file:de.codecentric.capturereplay.data.JsonDataMapper.java

private ObjectMapper createObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true);
    objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
    return objectMapper;
}

From source file:de.petendi.ethereum.secure.proxy.controller.SecureController.java

private String dispatch(byte[] bytes) {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    WrappedResponse wrappedResponse = new WrappedResponse();
    try {//  ww  w.ja  v a  2 s. c  o  m
        WrappedRequest wrappedRequest = objectMapper.readValue(bytes, WrappedRequest.class);
        AllowedCommand allowedCommand = AllowedCommand.valueOf(wrappedRequest.getCommand());
        if (wrappedRequest.getCommand().startsWith("shh_") && !settings.isWhisperAllowed()) {
            throw new SecurityException("command not allowed: " + wrappedRequest.getCommand());
        }

        Object response = rpcClient.invoke(allowedCommand.toString(), wrappedRequest.getParameters(),
                Object.class, settings.getHeaders());
        wrappedResponse.setResponse(response);
        wrappedResponse.setSuccess(true);
    } catch (Throwable e) {
        wrappedResponse.setSuccess(false);
        wrappedResponse.setErrorMessage(e.getMessage());
    }
    try {
        return objectMapper.writeValueAsString(wrappedResponse);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:com.ikanow.aleph2.security.db.SessionDb.java

protected JsonNode serialize(Object session) {
    ObjectNode sessionOb = null;//from   w ww .  j  ava  2  s . c  o m
    if (session instanceof Session) {
        Session s = (Session) session;
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        sessionOb = mapper.createObjectNode();
        sessionOb.put("_id", s.getId().toString());
        sessionOb.put("last_access_time", s.getLastAccessTime().getTime());
        sessionOb.put("start_time_stamp", s.getStartTimestamp().getTime());
        sessionOb.put("timeout", s.getTimeout());
        sessionOb.put("host", s.getHost());
        ObjectNode attributesOb = sessionOb.putObject("attributes");
        for (Iterator<Object> it = s.getAttributeKeys().iterator(); it.hasNext();) {
            Object key = it.next();
            Object value = s.getAttribute(key);
            if (value != null) {
                // base64 encode objects in session
                logger.debug("Storing session attribute:" + key + "=" + value);
                attributesOb.put(escapeMongoCharacters("" + key), SerializableUtils.serialize(value));
            }
        }
    }
    return sessionOb;
}

From source file:com.github.yongchristophertang.engine.web.response.JsonResultTransformer.java

/**
 * Transform the json result to a list with T as its member class.
 *
 * @param clazz the type class of transformed list member object
 *///from  w  w  w  .  j a  va  2 s  .  c o  m
public <T> ResultTransform<List<T>> list(Class<T> clazz) {
    return result -> {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return expression == null
                ? mapper.readValue(result.getResponseStringContent(),
                        TypeFactory.defaultInstance().constructCollectionType(List.class, clazz))
                : mapper.readValue(
                        JsonPath.compile(expression).read(result.getResponseStringContent()).toString(),
                        TypeFactory.defaultInstance().constructCollectionType(List.class, clazz));
    };
}

From source file:com.github.yongchristophertang.engine.web.response.JsonResultTransformer.java

/**
 * Transform the json result to a map with K as its key class and V as its value class.
 *
 * @param keyClass   the type class of transformed map key object
 * @param valueClass the type class of transformed map value object
 *//*from   w w  w  . j a  v  a 2 s. c o m*/
public <K, V> ResultTransform<Map<K, V>> map(Class<K> keyClass, Class<V> valueClass) {
    return result -> {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return expression == null
                ? mapper.readValue(result.getResponseStringContent(),
                        TypeFactory.defaultInstance().constructMapLikeType(Map.class, keyClass, valueClass))
                : mapper.readValue(
                        JsonPath.compile(expression).read(result.getResponseStringContent()).toString(),
                        TypeFactory.defaultInstance().constructMapLikeType(Map.class, keyClass, valueClass));
    };
}

From source file:models.db.acentera.impl.ProjectImpl.java

public static JSONObject getProjectUserDetails(Long projectId, Long userId, User u) throws Exception {
    Logger.debug("getProjectUserDetails B1 ");
    Session s = (Session) HibernateSessionFactory.getSession();
    Criteria criteria = s.createCriteria(UserProjects.class);

    JSONArray jsoProjectUserArray = new JSONArray();
    JSONArray jsoUserArray = new JSONArray();
    JSONArray jsoProjectIdArray = new JSONArray();
    jsoProjectIdArray.add(projectId);/*from w  w  w  .  j a  v a  2  s.  c o  m*/

    Set<User> proessedUsers = new HashSet<User>();

    //Get informations about the current User if its in this project...
    //User theUser = UserImpl.getUserById(userId);

    //Verry Bad but we couldn't get the user / project mapping to work properly in restrictions...
    Logger.debug("getProjectUserDetails B2  ");
    List<UserProjects> lstUp = (List<UserProjects>) criteria
            .add(Restrictions.and(Restrictions.eq("project.id", projectId))).list();
    Logger.debug("getProjectUserDetails B2a  " + lstUp);

    UserProjects up = null;
    Iterator<UserProjects> itrUp = lstUp.iterator();
    while (itrUp.hasNext() && up == null) {
        UserProjects tmpUp = itrUp.next();
        if (tmpUp.getUser().getId().longValue() == userId) {
            up = tmpUp;
        }
    }

    Logger.debug("getProjectUserDetails Bb " + up);

    if (up == null) {
        Logger.debug("Returning null 2...");
        return null;
    }

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    ObjectWriter ow = mapper.writer();

    User projectUser = up.getUser();

    jsoProjectUserArray.add(projectUser.getId());
    JSONObject jsoUser = JSONObject.fromObject(mapper.writeValueAsString(projectUser));
    jsoUser.put("project", jsoProjectIdArray);
    jsoUser.put("project_id", projectId);

    //get current user Tag only..
    //Other tags will be gathered if end-user click on them..
    List<ProjectUserTags> tags = ProjectImpl.getUserProjectTags(up);
    JSONArray jsoTagsArr = new JSONArray();
    for (int i = 0; i < tags.size(); i++) {
        jsoTagsArr.add(JSONObject.fromObject(mapper.writeValueAsString(tags.get(i))));
    }

    //jsoUser.put("tags", mapper.writeValueAsString(userProject.getTags()));
    jsoUser.put("tags", jsoTagsArr);

    //Get the current user roles for this project...
    JSONArray jsRolesArray = new JSONArray();
    Set<ProjectTags> userRoles = ProjectImpl.getUserProjectRoles(up);
    Iterator<ProjectTags> itrRoles = userRoles.iterator();
    while (itrRoles.hasNext()) {
        ProjectTags userProjectRole = itrRoles.next();
        JSONObject role = JSONObject.fromObject(ow.writeValueAsString(userProjectRole));
        jsRolesArray.add(role);
    }
    jsoUser.put("roles", jsRolesArray);

    jsoUserArray.add(jsoUser);

    proessedUsers.add(projectUser);

    JSONObject jso = new JSONObject();
    jso.put("users", jsoUserArray);
    //jsoProject.put("users", jsoProjectUserArray);

    return jso;
}

From source file:com.github.yongchristophertang.engine.web.response.JsonResultTransformer.java

/**
 * Transform the json result to an instance of T.
 *
 * @param clazz the type class of transformed object
 *///w  w w  .  j  a va 2s .  c o  m
public <T> ResultTransform<T> object(Class<T> clazz) {
    return result -> {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        try {
            return expression == null ? mapper.readValue(result.getResponseStringContent(), clazz)
                    : mapper.readValue(
                            JsonPath.compile(expression).read(result.getResponseStringContent()).toString(),
                            clazz);
        } catch (JsonParseException e) {
            Objects.nonNull(expression);
            return clazz.cast(JsonPath.compile(expression).read(result.getResponseStringContent()));
        }
    };
}