Example usage for com.fasterxml.jackson.core JsonGenerator useDefaultPrettyPrinter

List of usage examples for com.fasterxml.jackson.core JsonGenerator useDefaultPrettyPrinter

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonGenerator useDefaultPrettyPrinter.

Prototype

public abstract JsonGenerator useDefaultPrettyPrinter();

Source Link

Document

Convenience method for enabling pretty-printing using the default pretty printer ( com.fasterxml.jackson.core.util.DefaultPrettyPrinter ).

Usage

From source file:io.pdef.json.JsonJacksonFormat.java

/** Writes an object to a writer as a JSON string, does not close the writer. */
public <T> void write(final PrintWriter writer, final T object, final DataTypeDescriptor<T> descriptor,
        final boolean indent) throws IOException {
    if (writer == null)
        throw new NullPointerException("writer");
    if (descriptor == null)
        throw new NullPointerException("descriptor");

    JsonGenerator generator = factory.createGenerator(writer);
    if (indent) {
        generator.useDefaultPrettyPrinter();
    }/*from  w  w w. j  a v a2s.  com*/

    write(object, descriptor, generator);
    generator.flush();
}

From source file:com.iflytek.edu.cloud.frame.spring.MappingJackson2HttpMessageConverterExt.java

@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {
    outputMessage.getHeaders().setContentType(MediaType.parseMediaType("application/json"));
    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
    JsonGenerator jsonGenerator = this.getObjectMapper().getFactory().createGenerator(outputMessage.getBody(),
            encoding);/*from   w w w . j  a v  a2  s  .c o m*/

    // A workaround for JsonGenerators not applying serialization features
    // https://github.com/FasterXML/jackson-databind/issues/12
    if (this.getObjectMapper().isEnabled(SerializationFeature.INDENT_OUTPUT)) {
        jsonGenerator.useDefaultPrettyPrinter();
    }

    String callBack = (String) RestContextHolder.getContext().getParam(Constants.SYS_PARAM_KEY_CALLBACK);
    try {
        if (StringUtils.hasText(callBack)) {
            String json = this.getObjectMapper().writeValueAsString(object);
            json = callBack + "( " + json + " )";
            outputMessage.getBody().write(json.getBytes(Charset.forName("UTF-8")));
            outputMessage.getBody().flush();
        } else {
            this.getObjectMapper().writeValue(jsonGenerator, object);
        }
    } catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}

From source file:com.github.hateoas.forms.spring.uber.UberJackson2HttpMessageConverter.java

@Override
protected void writeInternal(Object t, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    UberMessageModel uberModel = new UberMessageModel(t);
    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
    JsonGenerator jsonGenerator = this.objectMapper.getFactory().createGenerator(outputMessage.getBody(),
            encoding);//from w  w  w  .  j a  v a 2s  .  c  o  m

    // A workaround for JsonGenerators not applying serialization features
    // https://github.com/FasterXML/jackson-databind/issues/12
    if (this.objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
        jsonGenerator.useDefaultPrettyPrinter();
    }

    try {
        this.objectMapper.writeValue(jsonGenerator, uberModel);
    } catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}

From source file:de.escalon.hypermedia.spring.uber.UberJackson2HttpMessageConverter.java

@Override
protected void writeInternal(Object t, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    UberMessageModel uberModel = new UberMessageModel(t);
    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
    JsonGenerator jsonGenerator = this.objectMapper.getFactory().createGenerator(outputMessage.getBody(),
            encoding);// w w  w .j a v a 2 s  .c  o m

    // A workaround for JsonGenerators not applying serialization features
    // https://github.com/FasterXML/jackson-databind/issues/12
    if (this.objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
        jsonGenerator.useDefaultPrettyPrinter();
    }

    try {
        this.objectMapper.writeValue(jsonGenerator, uberModel);
    } catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }

}

From source file:tuwien.aic.crowdsourcing.util.MappingJackson2HttpMessageConverter.java

@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
    JsonGenerator jsonGenerator = this.objectMapper.getFactory().createJsonGenerator(outputMessage.getBody(),
            encoding);/* w w w  .  ja  v  a2 s . com*/
    try {
        if (this.prefixJson) {
            jsonGenerator.writeRaw("{} && ");
        }
        if (this.prettyPrint) {
            jsonGenerator.useDefaultPrettyPrinter();
        }
        this.objectMapper.writeValue(jsonGenerator, object);
    } catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}

From source file:de.ii.ogc.wfs.proxy.AbstractWfsProxyService.java

public JsonGenerator createJsonGenerator(OutputStream output) throws IOException {
    JsonGenerator json = jsonFactory.createGenerator(output);
    json.setCodec(jsonMapper);//  w  w  w. j ava2s.  c o m
    //if (useFormattedJsonOutput) {
    json.useDefaultPrettyPrinter();
    //}
    // Zum JSON debuggen hier einschalten.
    //JsonGenerator jsond = new JsonGeneratorDebug(json);
    return json;
}

From source file:net.solarnetwork.web.support.JSONView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    PropertyEditorRegistrar registrar = this.propertyEditorRegistrar;
    Enumeration<String> attrEnum = request.getAttributeNames();
    while (attrEnum.hasMoreElements()) {
        String key = attrEnum.nextElement();
        Object val = request.getAttribute(key);
        if (val instanceof PropertyEditorRegistrar) {
            registrar = (PropertyEditorRegistrar) val;
            break;
        }/*from ww  w .j a  v  a 2 s .c  o m*/
    }

    response.setCharacterEncoding(UTF8_CHAR_ENCODING);
    response.setContentType(getContentType());
    Writer writer = response.getWriter();
    if (this.includeParentheses) {
        writer.write('(');
    }
    JsonGenerator json = new JsonFactory().createGenerator(writer);
    json.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    if (indentAmount > 0) {
        json.useDefaultPrettyPrinter();
    }
    json.writeStartObject();
    for (String key : model.keySet()) {
        Object val = model.get(key);
        writeJsonValue(json, key, val, registrar);
    }
    json.writeEndObject();
    json.close();
    if (this.includeParentheses) {
        writer.write(')');
    }
}

From source file:org.usrz.libs.webtools.resources.ServeResource.java

private Response produce(String path) throws Exception {

    /* Basic check for null/empty path */
    if ((path == null) || (path.length() == 0))
        return NOT_FOUND;

    /* Get our resource file, potentially a ".less" file for CSS */
    Resource resource = manager.getResource(path);
    if ((resource == null) && path.endsWith(".css")) {
        path = path.substring(0, path.length() - 4) + ".less";
        resource = manager.getResource(path);
    }/*  w ww  . ja  va2 s  .c  om*/

    /* If the root is incorrect, log this, if not found, 404 it! */
    if (resource == null)
        return NOT_FOUND;

    /* Ok, we have a resource on disk, this can be potentially long ... */
    final String fileName = resource.getFile().getName();

    /* Check and validated our cache */
    Entry cached = cache.computeIfPresent(resource, (r, entry) -> entry.resource.hasChanged() ? null : entry);

    /* If we have no cache, we *might* want to cache something */
    if (cached == null) {

        /* What to do, what to do? */
        if ((fileName.endsWith(".css") && minify) || fileName.endsWith(".less")) {

            /* Lessify CSS and cache */
            xlog.debug("Lessifying resource \"%s\"", fileName);
            cached = new Entry(resource, lxess.convert(resource, minify), styleMediaType);

        } else if (fileName.endsWith(".js") && minify) {

            /* Uglify JavaScript and cache */
            xlog.debug("Uglifying resource \"%s\"", fileName);
            cached = new Entry(resource, uglify.convert(resource.readString(), minify, minify),
                    scriptMediaType);

        } else if (fileName.endsWith(".json")) {

            /* Strip comments and normalize JSON */
            xlog.debug("Normalizing JSON resource \"%s\"", fileName);

            /* All to do with Jackson */
            final Reader reader = resource.read();
            final StringWriter writer = new StringWriter();
            final JsonParser parser = json.createParser(reader);
            final JsonGenerator generator = json.createGenerator(writer);

            /* Not minifying? Means pretty printing! */
            if (!minify)
                generator.useDefaultPrettyPrinter();

            /* Get our schtuff through the pipeline */
            parser.nextToken();
            generator.copyCurrentStructure(parser);
            generator.flush();
            generator.close();
            reader.close();
            parser.close();

            /* Cached results... */
            cached = new Entry(resource, writer.toString(), jsonMediaType);

        }

        /* Do we have anything to cache? */
        if (cached != null) {
            xlog.debug("Caching resource \"%s\"", fileName);
            cache.put(resource, cached);
        }
    }

    /* Prepare our basic response from either cache or file */
    final ResponseBuilder response = Response.ok();
    if (cached != null) {

        /* Response from cache */
        xlog.trace("Serving cached resource \"%s\"", fileName);
        response.entity(cached.contents).lastModified(new Date(resource.lastModifiedAt())).type(cached.type);
    } else {

        /* Response from a file */
        xlog.trace("Serving file-based resource \"%s\"", fileName);

        /* If text/* or application/javascript, append encoding */
        MediaType type = MediaTypes.get(fileName);
        if (type.getType().equals("text") || scriptMediaType.isCompatible(type)) {
            type = type.withCharset(charsetName);
        }

        /* Our file is served! */
        response.entity(resource.getFile()).lastModified(new Date(resource.lastModifiedAt())).type(type);
    }

    /* Caching headers and build response */
    final Date expires = Date.from(Instant.now().plus(cacheDuration));
    return response.cacheControl(cacheControl).expires(expires).build();

}

From source file:org.resthub.web.converter.MappingJackson2XmlHttpMessageConverter.java

@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
    JsonGenerator jsonGenerator = this.objectMapper.getJsonFactory()
            .createJsonGenerator(outputMessage.getBody(), encoding);

    // A workaround for JsonGenerators not applying serialization features
    // https://github.com/FasterXML/jackson-databind/issues/12
    if (this.objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
        jsonGenerator.useDefaultPrettyPrinter();
    }//from  w ww .  java2 s  .  co m

    try {
        this.objectMapper.writeValue(jsonGenerator, object);
    } catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write XML: " + ex.getMessage(), ex);
    }
}

From source file:org.resthub.web.converter.MappingJackson2JsonHttpMessageConverter.java

@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
    JsonGenerator jsonGenerator = this.objectMapper.getJsonFactory()
            .createJsonGenerator(outputMessage.getBody(), encoding);

    // A workaround for JsonGenerators not applying serialization features
    // https://github.com/FasterXML/jackson-databind/issues/12
    if (this.objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
        jsonGenerator.useDefaultPrettyPrinter();
    }//from   w  w w  .  j  ava  2s  . c o  m

    try {
        if (this.prefixJson) {
            jsonGenerator.writeRaw("{} && ");
        }
        this.objectMapper.writeValue(jsonGenerator, object);
    } catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
}