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

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

Introduction

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

Prototype

@SuppressWarnings("resource")
public String writeValueAsString(Object value) throws JsonProcessingException 

Source Link

Document

Method that can be used to serialize any Java value as a String.

Usage

From source file:com.sugaronrest.restapicalls.methodcalls.Authentication.java

/**
 * Login to SugarCRM via REST API call.//from ww  w. java2  s .c om
 *
 *  @param loginRequest LoginRequest object.
 *  @return LoginResponse object.
 */
public static LoginResponse login(LoginRequest loginRequest) throws Exception {

    LoginResponse loginResponse = new LoginResponse();

    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        String passwordHash = new BigInteger(1, md5.digest(loginRequest.password.getBytes())).toString(16);

        Map<String, String> userCredentials = new LinkedHashMap<String, String>();
        userCredentials.put("user_name", loginRequest.username);
        userCredentials.put("password", passwordHash);

        Map<String, Object> auth = new LinkedHashMap<String, Object>();
        auth.put("user_auth", userCredentials);
        auth.put("application_name", "RestClient");

        ObjectMapper mapper = new ObjectMapper();
        String jsonAuthData = mapper.writeValueAsString(auth);

        Map<String, Object> request = new LinkedHashMap<String, Object>();
        request.put("method", "login");
        request.put("input_type", "json");
        request.put("response_type", "json");
        request.put("rest_data", auth);

        String jsonRequest = mapper.writeValueAsString(request);

        request.put("rest_data", jsonAuthData);

        HttpResponse response = Unirest.post(loginRequest.url).fields(request).asString();

        String jsonResponse = response.getBody().toString();
        loginResponse.setJsonRawRequest(jsonRequest);
        loginResponse.setJsonRawResponse(jsonResponse);

        Map<String, Object> responseObject = mapper.readValue(jsonResponse, Map.class);
        if (responseObject.containsKey("id")) {
            loginResponse.sessionId = (responseObject.get("id").toString());
            loginResponse.setStatusCode(response.getStatus());
            loginResponse.setError(null);
        } else {
            ErrorResponse errorResponse = mapper.readValue(jsonResponse, ErrorResponse.class);
            errorResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST);
            loginResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST);
            loginResponse.setError(errorResponse);
        }
    } catch (Exception exception) {
        ErrorResponse errorResponse = ErrorResponse.format(exception, exception.getMessage());
        loginResponse.setError(errorResponse);
    }

    return loginResponse;
}

From source file:de.qaware.cloud.deployer.commons.config.util.ContentTreeUtil.java

/**
 * Writes the specified content as a string in the specified format.
 *
 * @param contentType The format the object is written to.
 * @param object      The object that will be written.
 * @return The written object as string.
 * @throws ResourceConfigException If a error during object writing occurs.
 *///from  ww w.  j  a v a2 s .co m
public static String writeAsString(ContentType contentType, Object object) throws ResourceConfigException {
    try {
        ObjectMapper objectMapper = retrieveObjectMapper(contentType);
        return objectMapper.writeValueAsString(object);
    } catch (JsonProcessingException ex) {
        throw new ResourceConfigException(
                COMMONS_MESSAGE_BUNDLE.getMessage("DEPLOYER_COMMONS_ERROR_DURING_CONTENT_WRITING"), ex);
    }
}

From source file:org.bigloupe.web.monitor.util.JSONUtil.java

public static String formatJson(Object object) throws IOException {
    ObjectMapper om = new ObjectMapper();
    om.enable(SerializationFeature.INDENT_OUTPUT);
    om.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    return om.writeValueAsString(object);
}

From source file:org.dawnsci.commandserver.core.util.JSONUtils.java

/**
 * Generic way of sending a topic notification
 * @param connection - does not get closed afterwards nust be started before.
 * @param message/*from  w ww  .  ja v a  2 s.  c om*/
 * @param topicName
 * @param uri
 * @throws Exception
 */
private static final void sendTopic(Connection connection, Object message, String topicName, URI uri)
        throws Exception {

    // JMS messages are sent and received using a Session. We will
    // create here a non-transactional session object. If you want
    // to use transactions you should set the first parameter to 'true'
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    try {
        Topic topic = session.createTopic(topicName);

        MessageProducer producer = session.createProducer(topic);

        final ObjectMapper mapper = new ObjectMapper();

        // Here we are sending the message out to the topic
        TextMessage temp = session.createTextMessage(mapper.writeValueAsString(message));
        producer.send(temp, DeliveryMode.NON_PERSISTENT, 1, 5000);

    } finally {
        session.close();
    }
}

From source file:com.gtcgroup.jped.valid.helper.JpvValidationUtilHelper.java

/**
 * @param instance//w  w  w.  j av a2 s .co m
 * @return {@link String}
 */
public static String convertInstanceToJsonString(final Object instance) {

    final String methodName = "convertInstanceToJsonString";

    String result;
    try {

        final ObjectMapper objectMapper = new ObjectMapper();
        result = objectMapper.writeValueAsString(instance);

    } catch (final Exception e) {
        throw new JpvValidationException(
                new JpcBasicExceptionPO().setClassName(JpvValidationUtilHelper.CLASS_NAME)
                        .setMethodName(methodName).setMessage("The result."),
                e);
    }

    return result;
}

From source file:org.bigloupe.web.monitor.util.JSONUtil.java

/**
 * Writes object to the writer as JSON using Jackson and adds a new-line
 * before flushing./*  ww  w.jav a2  s .c o m*/
 * 
 * @param writer
 *            the writer to write the JSON to
 * @param object
 *            the object to write as JSON
 * @throws IOException
 *             if the object can't be serialized as JSON or written to the
 *             writer
 */
public static void writeJson(Writer writer, Object object) throws IOException {
    ObjectMapper om = new ObjectMapper();
    om.enable(SerializationFeature.INDENT_OUTPUT);
    om.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);

    writer.write(om.writeValueAsString(object));
    writer.write("\n");
    writer.flush();
}

From source file:io.samsungsami.example.SAMInBLEws.SAMIDeviceManager.java

/**
 * Returns a JSON string from a credentials object
 * @return//w  w  w.  jav a2  s .c  om
 */
public static String toJson(io.samsungsami.model.Device device) {
    ObjectMapper mapper = new ObjectMapper();
    String json = null;
    try {
        json = mapper.writeValueAsString(device);
    } catch (JsonGenerationException ex) {
        ex.printStackTrace();
    } catch (JsonMappingException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return json;
}

From source file:org.apache.drill.common.logical.LogicalPlan.java

/** Parses a logical plan. */
public static LogicalPlan parse(DrillConfig config, String planString) {
    ObjectMapper mapper = config.getMapper();
    try {/*from   w  w  w .  ja va2 s . co m*/
        LogicalPlan plan = mapper.readValue(planString, LogicalPlan.class);
        System.out.println(mapper.writeValueAsString(plan));
        return plan;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.trentorise.opendata.commons.test.jackson.OdtJacksonTester.java

/**
 * Tests that the provided object can be converted to json and
 * reconstructed. Also logs the json with the provided logger at FINE
 * level./*  w  w w  .  ja v a 2  s  .  c o  m*/
 *
 * @return the reconstructed object
 */
public static <T> T testJsonConv(ObjectMapper om, Logger logger, @Nullable T obj) {

    checkNotNull(om);
    checkNotNull(logger);

    T recObj;

    try {
        String json = om.writeValueAsString(obj);
        logger.log(Level.FINE, "json = {0}", json);
        Object ret = om.readValue(json, obj.getClass());
        recObj = (T) ret;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

    assertEquals(obj, recObj);
    return recObj;
}

From source file:it.larusba.neo4j.jdbc.http.driver.Neo4jStatement.java

/**
 * Convert the list of query to a JSON compatible with Neo4j endpoint.
 *
 * @param queries List of cypher queries.
 * @return The JSON string that correspond to the body of the API call
 *///from   w w w  .  j ava 2  s.c  o  m
public static String toJson(List<Neo4jStatement> queries, ObjectMapper mapper) throws SQLException {
    StringBuffer sb = new StringBuffer();
    try {
        sb.append("{\"statements\":");
        sb.append(mapper.writeValueAsString(queries));
        sb.append("}");

    } catch (JsonProcessingException e) {
        throw new SQLException("Can't convert Cypher statement(s) into JSON");
    }
    return sb.toString();
}