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

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

Introduction

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

Prototype

public JsonGenerator setCharacterEscapes(CharacterEscapes esc) 

Source Link

Document

Method for defining custom escapes factory uses for JsonGenerator s it creates.

Usage

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", "");
    }// ww w  .ja  v  a 2s  . com
    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();
        }
    }
}