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

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

Introduction

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

Prototype

public abstract void writeEndObject() throws IOException, JsonGenerationException;

Source Link

Document

Method for writing closing marker of a JSON Object value (character '}'; plus possible white space decoration if pretty-printing is enabled).

Usage

From source file:com.greplin.gec.GecLog4jAppender.java

/**
 * Writes the current context to the given JsonGenerator.
 * @param generator where to write the context
 * @throws IOException if there are IO errors in the destination
 *///  w  ww  .ja  va  2  s .  co  m
private void writeContext(final JsonGenerator generator) throws IOException {
    Map<String, String> context = GecContext.get();
    if (!context.isEmpty()) {
        generator.writeFieldName("context");
        generator.writeStartObject();
        for (Map.Entry<String, String> entry : context.entrySet()) {
            generator.writeStringField(entry.getKey(), entry.getValue());
        }
        generator.writeEndObject();
    }
}

From source file:eionet.meta.exports.json.VocabularyJSONOutputHelper.java

/**
 * Writes JSON to output stream.// ww w .j  a v  a2 s .co  m
 * <p>
 * NOTE: For readability purposes, nested blocks are used in this method while generating json contents.
 * </p>
 *
 * @param out
 *            output stream
 * @param vocabulary
 *            vocabulary base uri
 * @param concepts
 *            list of vocabulary concepts
 * @param language
 *            language for the preferred label
 * @throws java.io.IOException
 *             if error in I/O
 */
public static void writeJSON(OutputStream out, VocabularyFolder vocabulary, List<VocabularyConcept> concepts,
        String language) throws IOException {
    OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");

    JsonFactory f = new JsonFactory();
    JsonGenerator generator = f.createGenerator(out);
    generator.useDefaultPrettyPrinter();

    language = StringUtils.trimToNull(language);
    boolean checkLanguage = StringUtils.isNotBlank(language);

    List<String> relationalDataElemIdentifiers = new ArrayList<String>();
    relationalDataElemIdentifiers.add(BROADER);
    relationalDataElemIdentifiers.add(NARROWER);

    // start json object
    generator.writeStartObject();
    // add context
    generator.writeObjectFieldStart(JSON_LD_CONTEXT);
    {
        generator.writeStringField(JSON_LD_BASE, VocabularyFolder.getBaseUri(vocabulary));
        generator.writeStringField(VocabularyOutputHelper.LinkedDataNamespaces.SKOS,
                VocabularyOutputHelper.LinkedDataNamespaces.SKOS_NS);
        generator.writeStringField(JSON_LD_CONCEPTS, SKOS_CONCEPT);
        generator.writeStringField(PREF_LABEL, SKOS_PREF_LABEL);
        for (String dataElemShortIdentifier : relationalDataElemIdentifiers) {
            generator.writeStringField(dataElemShortIdentifier, DATA_ELEM_MAP.get(dataElemShortIdentifier));
        }
        generator.writeStringField(JSON_LD_LANGUAGE,
                StringUtils.isNotBlank(language) ? language : DEFAULT_LANGUAGE);
    }
    generator.writeEndObject();
    // start writing concepts...
    generator.writeArrayFieldStart(JSON_LD_CONCEPTS);
    // iterate on concepts
    for (VocabularyConcept concept : concepts) {
        generator.writeStartObject();
        {
            generator.writeStringField(JSON_LD_ID, concept.getIdentifier());
            generator.writeStringField(JSON_LD_TYPE, SKOS_CONCEPT);
            // start writing prefLabels
            generator.writeArrayFieldStart(PREF_LABEL);
            {
                String label;
                String labelLang;
                if (checkLanguage) {
                    List<DataElement> dataElementValuesByNameAndLang = VocabularyOutputHelper
                            .getDataElementValuesByNameAndLang(SKOS_PREF_LABEL, language,
                                    concept.getElementAttributes());
                    if (dataElementValuesByNameAndLang != null && dataElementValuesByNameAndLang.size() > 0) {
                        label = dataElementValuesByNameAndLang.get(0).getAttributeValue();
                        labelLang = language;
                    } else {
                        dataElementValuesByNameAndLang = VocabularyOutputHelper
                                .getDataElementValuesByNameAndLang(SKOS_PREF_LABEL, DEFAULT_LANGUAGE,
                                        concept.getElementAttributes());
                        if (dataElementValuesByNameAndLang != null
                                && dataElementValuesByNameAndLang.size() > 0) {
                            label = dataElementValuesByNameAndLang.get(0).getAttributeValue();
                        } else {
                            label = concept.getLabel();
                        }
                        labelLang = DEFAULT_LANGUAGE;
                    }
                    generator.writeStartObject();
                    {
                        generator.writeStringField(JSON_LD_VALUE, label);
                        generator.writeStringField(JSON_LD_LANGUAGE, labelLang);
                    }
                    generator.writeEndObject();
                } else {
                    generator.writeStartObject();
                    {
                        generator.writeStringField(JSON_LD_VALUE, concept.getLabel());
                        generator.writeStringField(JSON_LD_LANGUAGE, DEFAULT_LANGUAGE);
                    }
                    generator.writeEndObject();
                    List<DataElement> dataElementValuesByName = VocabularyOutputHelper
                            .getDataElementValuesByName(SKOS_PREF_LABEL, concept.getElementAttributes());
                    if (dataElementValuesByName != null && dataElementValuesByName.size() > 0) {
                        for (DataElement elem : dataElementValuesByName) {
                            generator.writeStartObject();
                            {
                                generator.writeStringField(JSON_LD_VALUE, elem.getAttributeValue());
                                generator.writeStringField(JSON_LD_LANGUAGE, elem.getAttributeLanguage());
                            }
                            generator.writeEndObject();
                        }
                    }
                }
            }
            // end writing prefLabels
            generator.writeEndArray();
            // write data elements
            for (String shortDataElemIdentifier : relationalDataElemIdentifiers) {
                // check if it has this element
                List<DataElement> dataElementValuesByName = VocabularyOutputHelper.getDataElementValuesByName(
                        DATA_ELEM_MAP.get(shortDataElemIdentifier), concept.getElementAttributes());
                if (dataElementValuesByName != null && dataElementValuesByName.size() > 0) {
                    // start writing element values
                    generator.writeArrayFieldStart(shortDataElemIdentifier);
                    for (DataElement elem : dataElementValuesByName) {
                        generator.writeStartObject();
                        {
                            generator.writeStringField(JSON_LD_ID, elem.getRelatedConceptIdentifier());
                        }
                        generator.writeEndObject();
                    }
                    // end writing element values
                    generator.writeEndArray();
                }
            }
        }
        // end writing concept
        generator.writeEndObject();
    } // end of iteration on concepts
    generator.writeEndArray();
    // end of vocabulary name
    generator.writeEndObject();

    // close writer and stream
    generator.close();
    osw.close();
}

From source file:com.google.openrtb.json.OpenRtbNativeJsonWriter.java

/**
 * Serializes a {@link NativeRequest} to JSON, with a provided {@link JsonGenerator}
 * which allows several choices of output and encoding.
 *//*from w w w  .  j  a  va 2  s . com*/
public final void writeNativeRequest(NativeRequest req, JsonGenerator gen) throws IOException {
    gen.writeStartObject();
    if (factory().isRootNativeField()) {
        gen.writeObjectFieldStart("native");
    }
    writeNativeRequestFields(req, gen);
    writeExtensions(req, gen);
    if (factory().isRootNativeField()) {
        gen.writeEndObject();
    }
    gen.writeEndObject();
    gen.flush();
}

From source file:com.google.openrtb.json.OpenRtbNativeJsonWriter.java

/**
 * Serializes a {@link NativeResponse} to JSON, with a provided {@link JsonGenerator}
 * which allows several choices of output and encoding.
 *//*from   w w w  .  j  a  va  2 s  . co  m*/
public final void writeNativeResponse(NativeResponse resp, JsonGenerator gen) throws IOException {
    gen.writeStartObject();
    if (factory().isRootNativeField()) {
        gen.writeObjectFieldStart("native");
    }
    writeNativeResponseFields(resp, gen);
    writeExtensions(resp, gen);
    if (factory().isRootNativeField()) {
        gen.writeEndObject();
    }
    gen.writeEndObject();
    gen.flush();
}

From source file:com.predic8.membrane.core.interceptor.apimanagement.statistics.AMStatisticsCollector.java

private String collectExchangeDataFrom(Exchange exc, String apiKey) throws IOException {
    JsonGenerator gen = getAndResetJsonGenerator();

    try {//from   ww  w . j a  va  2 s. com
        gen.writeStartObject();
        gen.writeObjectField("excId", exc.getId());
        gen.writeObjectField("excApiKey", apiKey);
        gen.writeObjectFieldStart("Request");
        collectFromMessage(gen, exc.getRequest());
        gen.writeEndObject();
        gen.writeObjectFieldStart("Response");
        collectFromMessage(gen, exc.getResponse());
        gen.writeEndObject();
        gen.writeEndObject();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return getStringFromJsonGenerator();
}

From source file:com.netflix.spectator.tdigest.Json.java

/** Encode the measurement using the generator. */
void encode(Map<String, String> commonTags, TDigestMeasurement m, JsonGenerator gen) throws IOException {
    TDigest digest = m.value();/*from   w  w w  .  j  a  v a  2s  . c  o  m*/
    digest.compress();
    ByteBuffer buf = ByteBuffer.allocate(digest.byteSize());
    digest.asBytes(buf);

    gen.writeStartArray();
    gen.writeStartObject();
    gen.writeStringField("name", m.id().name());
    for (Map.Entry<String, String> e : commonTags.entrySet()) {
        gen.writeStringField(e.getKey(), e.getValue());
    }
    for (Tag t : m.id().tags()) {
        gen.writeStringField(t.key(), t.value());
    }
    gen.writeEndObject();
    gen.writeNumber(m.timestamp());
    gen.writeBinary(buf.array());
    gen.writeEndArray();
}

From source file:org.bndtools.rt.repository.server.RepositoryResourceComponent.java

@GET
@Path("bundles")
@Produces(MediaType.APPLICATION_JSON)/*  w  w  w .j av  a  2 s  .co m*/
public Response listBundles(@Context UriInfo uriInfo) throws Exception {
    MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
    List<String> patterns = queryParams.get("pattern");
    if (patterns == null || patterns.isEmpty())
        return Response.status(Status.BAD_REQUEST).entity("Bundle listing requires 'pattern' query parameter.")
                .build();

    UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder().path("{bsn}");
    StringWriter writer = new StringWriter();
    JsonGenerator generator = jsonFactory.createJsonGenerator(writer);
    generator.writeStartArray();

    for (String pattern : patterns) {
        List<String> list = repo.list(pattern);
        for (String bsn : list) {
            generator.writeStartObject();
            generator.writeStringField("bsn", bsn);
            generator.writeStringField("href", uriBuilder.build(bsn).toString());
            generator.writeEndObject();
        }
    }
    generator.writeEndArray();
    generator.close();

    return Response.ok(writer.toString(), MediaType.APPLICATION_JSON).build();
}

From source file:com.attribyte.essem.es.MinMaxQuery.java

@Override
public void generate(final JsonGenerator generator) throws IOException {
    generator.writeStartObject();/*from w  ww.j  av  a2  s . c  o m*/
    {
        generator.writeObjectFieldStart("range");
        {
            generator.writeObjectFieldStart(term);
            {
                if (endpointValue instanceof Float || endpointValue instanceof Double) {
                    generator.writeNumberField(mode.op, endpointValue.doubleValue());
                } else {
                    generator.writeNumberField(mode.op, endpointValue.longValue());
                }
            }
            generator.writeEndObject();
        }
        generator.writeEndObject();
    }
    generator.writeEndObject();
}

From source file:io.gravitee.definition.jackson.datatype.services.healthcheck.ser.RequestSerializer.java

@Override
public void serialize(Request request, JsonGenerator jgen, SerializerProvider provider) throws IOException {
    jgen.writeStartObject();/*from ww w  .  j ava 2s  . c  o m*/
    jgen.writeStringField("uri", request.getUri());
    jgen.writeStringField("method", request.getMethod().name());

    if (request.getHeaders() != null && !request.getHeaders().isEmpty()) {
        jgen.writeArrayFieldStart("headers");

        request.getHeaders().forEach(httpHeader -> {
            try {
                jgen.writeStartObject();
                jgen.writeStringField("name", httpHeader.getName());
                jgen.writeStringField("value", httpHeader.getValue());
                jgen.writeEndObject();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        jgen.writeEndArray();
    }
    if (request.getBody() != null && !request.getBody().isEmpty()) {
        jgen.writeStringField("body", request.getBody());
    }
    jgen.writeEndObject();
}

From source file:ninja.leaping.configurate.json.JSONConfigurationLoader.java

private void generateObject(JsonGenerator generator, ConfigurationNode node) throws IOException {
    if (!node.hasMapChildren()) {
        throw new IOException("Node passed to generateObject does not have map children!");
    }/*w w w .  ja va  2 s .  co m*/
    generator.writeStartObject();
    for (Map.Entry<Object, ? extends ConfigurationNode> ent : node.getChildrenMap().entrySet()) {
        generator.writeFieldName(ent.getKey().toString());
        generateValue(generator, ent.getValue());
    }
    generator.writeEndObject();

}