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

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

Introduction

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

Prototype

public void writeStringField(String fieldName, String value) throws IOException, JsonGenerationException 

Source Link

Document

Convenience method for outputting a field entry ("member") that has a String value.

Usage

From source file:com.ibm.ws.lars.rest.FrontPage.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType(MediaType.APPLICATION_JSON);
    resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
    PrintWriter printWriter = resp.getWriter();

    List<AssetFilter> filters = new ArrayList<>();
    filters.add(new AssetFilter("state",
            Arrays.asList(new Condition[] { new Condition(Operation.EQUALS, "published") })));
    int assetCount = serviceLayer.countAllAssets(filters, null);

    JsonGenerator frontPageJsonGenerator = new JsonFactory().createGenerator(printWriter);
    frontPageJsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter());

    frontPageJsonGenerator.writeStartObject();
    frontPageJsonGenerator.writeStringField("serverName", "LARS");
    frontPageJsonGenerator.writeNumberField("assetCount", assetCount);
    frontPageJsonGenerator.writeEndObject();

    frontPageJsonGenerator.flush();/*from   w  w w  .  ja v  a2  s . c  o m*/
    frontPageJsonGenerator.close();
}

From source file:com.netflix.discovery.converters.jackson.ApplicationsJsonBeanSerializer.java

@Override
protected void serializeFields(Object bean, JsonGenerator jgen0, SerializerProvider provider)
        throws IOException {
    super.serializeFields(bean, jgen0, provider);
    Applications applications = (Applications) bean;

    if (applications.getVersion() != null) {
        jgen0.writeStringField(versionKey, Long.toString(applications.getVersion()));
    }//  w  ww .j  a v  a  2s. c om
    if (applications.getAppsHashCode() != null) {
        jgen0.writeStringField(appsHashCodeKey, applications.getAppsHashCode());
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.brat.internal.model.BratAttributeDrawingDecl.java

@Override
public void write(JsonGenerator aJG) throws IOException {
    aJG.writeFieldName("values");
    aJG.writeStartObject();//from   www  .  j av  a 2  s.  c o m
    for (String value : attributeDecl.getValues()) {
        aJG.writeFieldName(value);
        aJG.writeStartObject();
        aJG.writeStringField("glyph", value);
        aJG.writeEndObject();
    }
    aJG.writeEndObject();
}

From source file:de.fraunhofer.iosb.ilt.sta.serialize.DataArrayValueSerializer.java

@Override
public void serialize(DataArrayValue value, JsonGenerator gen, SerializerProvider serializers)
        throws IOException, JsonProcessingException {
    gen.writeStartObject();/*  w ww  .  j  a v a2 s .c o  m*/
    Datastream datastream = value.getDatastream();
    if (datastream != null) {
        gen.writeStringField("Datastream@iot.navigationLink", datastream.getNavigationLink());
    }
    MultiDatastream multiDatastream = value.getMultiDatastream();
    if (multiDatastream != null) {
        gen.writeStringField("MultiDatastream@iot.navigationLink", multiDatastream.getNavigationLink());
    }
    gen.writeObjectField("components", value.getComponents());
    int count = value.getDataArray().size();
    if (count >= 0) {
        gen.writeNumberField("dataArray@iot.count", count);
    }
    gen.writeFieldName("dataArray");
    gen.writeObject(value.getDataArray());
    gen.writeEndObject();
}

From source file:com.googlecode.jmxtrans.model.output.SensuWriter.java

private void serialize(Server server, Query query, List<Result> results, OutputStream outputStream)
        throws IOException {
    JsonGenerator g = jsonFactory.createGenerator(outputStream, JsonEncoding.UTF8);
    g.useDefaultPrettyPrinter();//from   w  ww.j  a v a 2  s  . c o m
    g.writeStartObject();
    g.writeStringField("name", "jmxtrans");
    g.writeStringField("type", "metric");
    g.writeStringField("handler", handler);

    StringBuilder jsonoutput = new StringBuilder();
    List<String> typeNames = getTypeNames();
    for (Result result : results) {
        for (Map.Entry<String, Object> values : result.getValues().entrySet()) {
            if (isNumeric(values.getValue())) {
                Object value = values.getValue();
                jsonoutput.append(KeyUtils.getKeyString(server, query, result, values, typeNames, null))
                        .append(" ").append(value).append(" ")
                        .append(TimeUnit.SECONDS.convert(result.getEpoch(), TimeUnit.MILLISECONDS))
                        .append(System.getProperty("line.separator"));
            }
        }
    }
    g.writeStringField("output", jsonoutput.toString());
    g.writeEndObject();
    g.flush();
    g.close();
}

From source file:com.greglturnquist.embeddablesdr.SystemDependencySerializer.java

@Override
public void serialize(final SystemDependency systemDependency, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonGenerationException {

    Link link = entityLinks.linkToSingleResource(System.class, systemDependency.getTarget().getId());

    jgen.writeStartObject();/*from  w  w  w.j a  v  a  2s .  com*/
    jgen.writeStringField("description", systemDependency.getDescription());
    jgen.writeObjectFieldStart("_links");
    jgen.writeObjectFieldStart("target");
    jgen.writeStringField("href", link.getHref());
    jgen.writeEndObject();
    jgen.writeEndObject();
    jgen.writeEndObject();
}

From source file:de.terrestris.shogun.security.ShogunAuthProcessingFilter.java

/**
 * On successful authentication by an Authentication Manager of Spring Security
 * we intercept with this method  and change the respone to include the ROLES of
 * the logged in user.//from   www. j a  va  2s .c o m
 * This way we can react on the ROLES and redirect accordingly within the requesting login form (here login.js)
 *
 * @see WebContent/client/login.js
 */
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        Authentication authResult) throws IOException, ServletException {
    SecurityContextHolder.getContext().setAuthentication(authResult);

    SavedRequestAwareAuthenticationSuccessHandler srh = new SavedRequestAwareAuthenticationSuccessHandler();
    this.setAuthenticationSuccessHandler(srh);
    srh.setRedirectStrategy(new RedirectStrategy() {
        @Override
        public void sendRedirect(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                String s) throws IOException {
            //do nothing, no redirect
        }
    });
    super.successfulAuthentication(request, response, authResult);

    // build a comma separated string of the ROLES
    String authorityText = StringUtils.join(authResult.getAuthorities(), ",");

    // write the servlet return object
    HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
    Writer out = responseWrapper.getWriter();
    JsonFactory jsonFactory = new JsonFactory();
    JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(out);
    jsonGenerator.writeStartObject();
    jsonGenerator.writeBooleanField("success", true);
    jsonGenerator.writeStringField("name", authResult.getName());
    jsonGenerator.writeStringField("role", authorityText);
    jsonGenerator.writeEndObject();
    jsonGenerator.close();
}

From source file:com.cedarsoft.serialization.serializers.jackson.ApplicationSerializer.java

@Override
public void serialize(@Nonnull JsonGenerator serializeTo, @Nonnull Application object,
        @Nonnull Version formatVersion) throws IOException, JsonProcessingException {
    verifyVersionReadable(formatVersion);
    //name//w  w  w .j a v a 2s .  c  o m
    serializeTo.writeStringField(PROPERTY_NAME, object.getName());
    //version
    serialize(object.getVersion(), Version.class, PROPERTY_VERSION, serializeTo, formatVersion);
}

From source file:com.sdl.odata.renderer.json.writer.JsonServiceDocumentWriter.java

/**
 * The main method for Writer./*from w  w w .jav  a 2s  .c o m*/
 * It builds the service root document according to spec.
 *
 * @return output in json
 * @throws ODataRenderException If unable to render the json service document
 */
public String buildJson() throws ODataRenderException {
    LOG.debug("Start building Json service root document");
    try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
        JsonGenerator jsonGenerator = JSON_FACTORY.createGenerator(stream, JsonEncoding.UTF8);
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField(CONTEXT, getContextURL(uri, entityDataModel));
        jsonGenerator.writeArrayFieldStart(VALUE);

        List<EntitySet> entities = entityDataModel.getEntityContainer().getEntitySets();
        for (EntitySet entity : entities) {
            if (entity.isIncludedInServiceDocument()) {
                writeObject(jsonGenerator, entity);
            }
        }

        List<Singleton> singletons = entityDataModel.getEntityContainer().getSingletons();
        for (Singleton singleton : singletons) {
            writeObject(jsonGenerator, singleton);
        }

        jsonGenerator.writeEndArray();
        jsonGenerator.writeEndObject();
        jsonGenerator.close();
        return stream.toString(StandardCharsets.UTF_8.name());
    } catch (IOException e) {
        throw new ODataRenderException("It is unable to render service document", e);
    }
}

From source file:com.msopentech.odatajclient.engine.data.json.JSONPropertySerializer.java

/**
 * {@inheritDoc }/*w  ww  . ja  v a2  s.c o  m*/
 */
@Override
public void serialize(final JSONProperty property, final JsonGenerator jgen, final SerializerProvider provider)
        throws IOException, JsonProcessingException {

    jgen.writeStartObject();

    if (property.getMetadata() != null) {
        jgen.writeStringField(ODataConstants.JSON_METADATA, property.getMetadata().toASCIIString());
    }

    final Element content = property.getContent();
    if (XMLUtils.hasOnlyTextChildNodes(content)) {
        jgen.writeStringField(ODataConstants.JSON_VALUE, content.getTextContent());
    } else {
        try {
            final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
            final Document document = builder.newDocument();
            final Element wrapper = document.createElement(ODataConstants.ELEM_PROPERTY);

            if (XMLUtils.hasElementsChildNode(content)) {
                wrapper.appendChild(document.renameNode(document.importNode(content, true), null,
                        ODataConstants.JSON_VALUE));

                DOMTreeUtils.writeSubtree(jgen, wrapper);
            } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                wrapper.appendChild(document.renameNode(document.importNode(content, true), null,
                        ODataConstants.JSON_VALUE));

                DOMTreeUtils.writeSubtree(jgen, wrapper, true);
            } else {
                DOMTreeUtils.writeSubtree(jgen, content);
            }
        } catch (Exception e) {
            throw new JsonParseException("Cannot serialize property", JsonLocation.NA, e);
        }
    }

    jgen.writeEndObject();
}