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

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

Introduction

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

Prototype

public ObjectWriter writerWithDefaultPrettyPrinter() 

Source Link

Document

Factory method for constructing ObjectWriter that will serialize objects using the default pretty printer for indentation

Usage

From source file:com.ubershy.streamsis.project.ProjectSerializator.java

/**
 * Tells if {@link CuteProject} class is written nicely by programmer and can be serialized. <br>
 *
 * @return true, if {@link CuteProject} can be serialized
 *///from   www.  j  a  v a  2s .c  o  m
public static boolean canSerializeProjectClass() {
    ObjectMapper mapper = new ObjectMapper();
    boolean bool = mapper.writerWithDefaultPrettyPrinter().canSerialize(CuteProject.class);
    return bool;
}

From source file:com.sdl.odata.renderer.util.PrettyPrinter.java

/**
 * Pretty-print a given Json./* www  .  j  a v a 2s  . c o m*/
 *
 * @param json The not-formatted Json.
 * @return The pretty-printed Json
 * @throws IOException
 */
public static String prettyPrintJson(String json) throws IOException {

    ObjectMapper objectMapper = new ObjectMapper();
    Object jsonObject = objectMapper.readValue(json, Object.class);

    return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
}

From source file:de.javagl.jgltf.model.io.JsonUtils.java

/**
 * Creates a formatted (pretty-printed, indented) representation of
 * the given JSON string. The details of the formatting are not 
 * specified. If there is any error during this process, then a 
 * warning will be printed and the given string will be returned.
 * //from   w w  w  .  j  a  v  a 2  s  .  c  om
 * @param jsonString The input JSON string
 * @return The formatted JSON string
 */
public static String format(String jsonString) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        Object object = mapper.readValue(jsonString, Object.class);
        String formattedJsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
        return formattedJsonString;
    } catch (IOException e) {
        logger.warning(e.getMessage());
        return jsonString;
    }
}

From source file:models.Collection.java

public static RestResponse findByID(Long id, String token) throws IOException {
    RestResponse restResponse = new RestResponse();
    //TODO insecure ssl hack
    HttpClient httpClient = new DefaultHttpClient();
    SSLSocketFactory sf = (SSLSocketFactory) httpClient.getConnectionManager().getSchemeRegistry()
            .getScheme("https").getSocketFactory();
    sf.setHostnameVerifier(new AllowAllHostnameVerifier());

    HttpGet request = new HttpGet(Application.baseRestUrl + "/collections/" + id + "?expand=all");
    request.setHeader("Accept", "application/json");
    request.addHeader("Content-Type", "application/json");
    request.addHeader("rest-dspace-token", token);
    HttpResponse httpResponse = httpClient.execute(request);

    JsonNode collNode = Json.parse(httpResponse.getEntity().getContent());

    Collection collection = new Collection();

    if (collNode.size() > 0) {
        collection = Collection.parseCollectionFromJSON(collNode);
    }//from  w  w  w .  j ava2 s  . com

    restResponse.httpResponse = httpResponse;
    restResponse.endpoint = request.getURI().toString();

    ObjectMapper mapper = new ObjectMapper();
    String pretty = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(collection);
    restResponse.jsonString = pretty;

    restResponse.modelObject = collection;

    return restResponse;
}

From source file:com.github.yongchristophertang.engine.java.LoggerProxyHelper.java

private static String toPrinterString(Object obj, boolean pretty) {
    /*/*from  ww w . ja  va2 s  .  c  o  m*/
     * returns true if an object can be converted to a string which matches the regex pattern of ^([a-z]+\.)+[a-zA-Z]+@\w+$ that is
     * the official default object toString implementation
     */
    if (!obj.toString().matches("^([a-z]+\\.)+[a-zA-Z]+@\\w+$")) {
        return obj.toString();
    }

    ObjectMapper mapper = new ObjectMapper();
    try {
        return obj.getClass().getSimpleName() + ": "
                + (pretty ? mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj)
                        : mapper.writeValueAsString(obj));
    } catch (JsonProcessingException e) {
        return "The object has not implemented toString() method and cannot be serialized to a string either";
    }
}

From source file:com.ubershy.streamsis.project.ProjectSerializator.java

/**
 * Serialize {@link CuteProject} to string.
 *
 * @param project//from  w ww.  ja  v  a  2  s .co m
 *            the {@link CuteProject} to serialize
 * @return the string in JSON format
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static String serializeToString(CuteProject project) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    String serialized = null;
    try {
        serialized = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(project);
    } catch (JsonGenerationException e) {
        logger.error("CuteProject serializing to string fail: JsonGeneration error");
        e.printStackTrace();
        throw e;
    } catch (JsonMappingException e) {
        logger.error("CuteProject serializing to string fail: Mapping error");
        e.printStackTrace();
        throw e;
    } catch (IOException e) {
        logger.error("CuteProject serializing to string fail: IO error");
        throw e;
    }
    logger.debug("CuteProject serializing to string success");
    return serialized;
}

From source file:com.ubershy.streamsis.project.ProjectSerializator.java

/**
 * Serialize(save) {@link CuteProject} to file.
 *
 * @param project/*from w w w .  j  av a 2  s  .  c  o  m*/
 *            the {@link CuteProject} to serialize
 * @param path
 *            the path where file will be saved
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void serializeToFile(CuteProject project, String path) throws IOException {
    logger.info("Saving Project file: " + path);
    ObjectMapper mapper = new ObjectMapper();
    try {
        Util.createFileAndDirectoriesAtPath(path);
        mapper.writerWithDefaultPrettyPrinter().writeValue(new FileWriter(new File(path)), project);
    } catch (JsonGenerationException e) {
        logger.error("CuteProject saving fail: JsonGeneration error");
        e.printStackTrace();
        throw e;
    } catch (JsonMappingException e) {
        logger.error("CuteProject saving fail: Mapping error");
        e.printStackTrace();
        throw e;
    } catch (IOException e) {
        logger.error("CuteProject saving fail: IO error");
        throw e;
    }
    logger.info("CuteProject saving success");
}

From source file:com.gtcgroup.test.restful.helper.JprRequestUtilHelper.java

/**
 * @param requestContext/*from  w  w  w . j  av  a 2s .c  o m*/
 */
public static void filterIncomingJsonRequest(final ClientRequestContext requestContext) {

    final String methodName = "filterIncomingRequest";

    final StringBuilder message = new StringBuilder();
    message.append("JAX-RS ");
    message.append(requestContext.getMethod());
    message.append(": ");
    message.append(requestContext.getUri().toString());

    if (null != requestContext.getEntity()) {

        message.append("\n");
        final ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        try {
            message.append(
                    mapper.writerWithDefaultPrettyPrinter().writeValueAsString(requestContext.getEntity()));

        } catch (final Exception e) {
            throw new TestingException("Unable to log incoming request.", e);
        }
    }

    JpcLoggingCacheHelper.getLogger().logModeLifecycle(JprRequestUtilHelper.CLASS_NAME, methodName,
            message.toString());

    return;
}

From source file:com.gtcgroup.jped.rest.helper.JprRequestUtilHelper.java

/**
 * @param requestContext/*from  w w  w .  j av a 2 s  .c om*/
 */
public static void filterIncomingJsonRequest(final ClientRequestContext requestContext) {

    final String methodName = "filterIncomingRequest";

    final StringBuilder message = new StringBuilder();
    message.append("JAX-RS ");
    message.append(requestContext.getMethod());
    message.append(": ");
    message.append(requestContext.getUri().toString());

    if (null != requestContext.getEntity()) {

        message.append("\n");
        final ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        try {
            message.append(
                    mapper.writerWithDefaultPrettyPrinter().writeValueAsString(requestContext.getEntity()));

        } catch (final Exception e) {
            throw new JprConvertException(
                    new JpcBasicExceptionPO().setClassName(JprRequestUtilHelper.CLASS_NAME)
                            .setMessage("Unable to log incoming request."),
                    e);
        }
    }

    JpcLoggingCacheHelper.getLogger().logModeLifecycle(JprRequestUtilHelper.CLASS_NAME, methodName,
            message.toString());

    return;
}

From source file:controllers.IntegrationTest.java

private static void assertPretty(Result result) {
    String contentAsString = contentAsString(result);
    ObjectMapper mapper = new ObjectMapper();
    try {//  w  w  w .  j  ava 2 s.co  m
        JsonNode jsonNode = mapper.readTree(contentAsString);
        String prettyString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
        assertThat(contentAsString).isEqualTo(prettyString);
    } catch (Exception e) {
        e.printStackTrace();
    }
}