Example usage for com.fasterxml.jackson.databind ObjectWriter withDefaultPrettyPrinter

List of usage examples for com.fasterxml.jackson.databind ObjectWriter withDefaultPrettyPrinter

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectWriter withDefaultPrettyPrinter.

Prototype

public ObjectWriter withDefaultPrettyPrinter() 

Source Link

Document

Method that will construct a new instance that will use the default pretty printer for serialization.

Usage

From source file:com.neatresults.mgnltweaks.json.JsonBuilder.java

/**
 * Executes configured chain of operations and produces the json output.
 *//*from  www .ja v  a 2 s.c o  m*/
public String print() {

    ObjectWriter ow = mapper.writer();
    if (!inline) {
        ow = ow.withDefaultPrettyPrinter();
    }

    if (wrapForI18n) {
        node = new I18nNodeWrapper(node);
    }
    try {
        // total depth is that of starting node + set total by user
        totalDepth += node.getDepth();
        String json;
        if (childrenOnly) {
            Collection<EntryableContentMap> childNodes = new LinkedList<EntryableContentMap>();
            NodeIterator nodes = this.node.getNodes();
            asNodeStream(nodes).filter(this::isSearchInNodeType).map(this::cloneWith)
                    .forEach(builder -> childNodes.add(new EntryableContentMap(builder)));
            json = ow.writeValueAsString(childNodes);
        } else if (!allowOnlyNodeTypes.equals(".*")) {
            Collection<EntryableContentMap> childNodes = new LinkedList<EntryableContentMap>();
            NodeIterator nodes = this.node.getNodes();
            asNodeStream(nodes).filter(this::isSearchInNodeType)
                    .forEach(new PredicateSplitterConsumer<Node>(this::isOfAllowedDepthAndType,
                            allowedNode -> childNodes.add(new EntryableContentMap(this.cloneWith(allowedNode))),
                            allowedParent -> childNodes
                                    .addAll(this.getAllowedChildNodesContentMapsOf(allowedParent, 1))));
            json = ow.writeValueAsString(childNodes);

        } else {
            EntryableContentMap map = new EntryableContentMap(this);
            List<String> garbage = map.entrySet().stream()
                    .filter(entry -> entry.getValue() instanceof EntryableContentMap)
                    .filter(entry -> ((EntryableContentMap) entry.getValue()).entrySet().isEmpty())
                    .map(entry -> entry.getKey()).collect(Collectors.toList());
            garbage.stream().forEach(key -> map.remove(key));
            json = ow.writeValueAsString(map);
        }

        if (StringUtils.isNotEmpty(preexisingJson)) {
            String trimmedJson = preexisingJson.trim();
            if (trimmedJson.endsWith("}")) {
                json = "[" + preexisingJson + "," + json + "]";
            } else if (trimmedJson.endsWith("]")) {
                json = StringUtils.substringBeforeLast(preexisingJson, "]")
                        + (trimmedJson.equals("[]") ? "" : ",") + json + "]";
            }
        }
        if (escapeBackslash) {
            json = ESCAPES.matcher(json).replaceAll("\\\\\\\\");
        }
        return json;
    } catch (JsonProcessingException | RepositoryException e) {
        log.debug("Failed to generate JSON string", e);
    }

    return "{ }";
}

From source file:com.github.jknack.handlebars.Jackson2Helper.java

@Override
public CharSequence apply(final Object context, final Options options) throws IOException {
    if (context == null) {
        return options.hash("default", "");
    }/*  www  .  j  a v  a2s.c o  m*/
    String viewName = options.hash("view", "");
    JsonGenerator generator = null;
    try {
        final ObjectWriter writer;
        // do we need to use a view?
        if (!isEmpty(viewName)) {
            Class<?> viewClass = alias.get(viewName);
            if (viewClass == null) {
                viewClass = getClass().getClassLoader().loadClass(viewName);
            }
            writer = mapper.writerWithView(viewClass);
        } else {
            writer = mapper.writer();
        }
        JsonFactory jsonFactory = mapper.getFactory();

        SegmentedStringWriter output = new SegmentedStringWriter(jsonFactory._getBufferRecycler());

        // creates a json generator.
        generator = jsonFactory.createJsonGenerator(output);

        Boolean escapeHtml = options.hash("escapeHTML", Boolean.FALSE);
        // do we need to escape html?
        if (escapeHtml) {
            generator.setCharacterEscapes(new HtmlEscapes());
        }

        Boolean pretty = options.hash("pretty", Boolean.FALSE);

        // write the JSON output.
        if (pretty) {
            writer.withDefaultPrettyPrinter().writeValue(generator, context);
        } else {
            writer.writeValue(generator, context);
        }

        generator.close();

        return new Handlebars.SafeString(output.getAndClear());
    } catch (ClassNotFoundException ex) {
        throw new IllegalArgumentException(viewName, ex);
    } finally {
        if (generator != null && !generator.isClosed()) {
            generator.close();
        }
    }
}