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

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

Introduction

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

Prototype

public abstract void writeFieldName(SerializableString name) throws IOException, JsonGenerationException;

Source Link

Document

Method similar to #writeFieldName(String) , main difference being that it may perform better as some of processing (such as quoting of certain characters, or encoding into external encoding if supported by generator) can be done just once and reused for later calls.

Usage

From source file:ijfx.service.overlay.io.OverlaySerializer.java

private void saveLineOverlay(LineOverlay overlay, JsonGenerator jg) throws IOException {

    jg.writeStartObject();/*from  w ww.  j a va 2s. c om*/
    jg.writeStringField(JsonOverlayToken.OVERLAY_TYPE, JsonOverlayToken.LINE_OVERLAY);

    Double[] lineStart = Utils.extractArray(overlay::getLineStart, overlay.numDimensions());
    Double[] lineEnd = Utils.extractArray(overlay::getLineEnd, overlay.numDimensions());

    writeNumberArray(jg, JsonOverlayToken.BEGIN, lineStart);
    writeNumberArray(jg, JsonOverlayToken.END, lineEnd);

    ColorRGB fcolor = overlay.getFillColor();
    ColorRGB lcolor = overlay.getLineColor();

    Integer[] fill_color = { fcolor.getRed(), fcolor.getGreen(), fcolor.getBlue() };
    Integer[] line_color = { lcolor.getRed(), lcolor.getGreen(), lcolor.getBlue() };

    double width = overlay.getLineWidth();

    writeNumberArray(jg, JsonOverlayToken.FILL_COLOR, fill_color);
    writeNumberArray(jg, JsonOverlayToken.LINE_COLOR, line_color);

    jg.writeFieldName(JsonOverlayToken.LINE_WIDTH);
    jg.writeNumber(width);

    jg.writeEndObject();

}

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

@Override
public void generate(final JsonGenerator generator) throws IOException {
    generator.writeStartObject();//w ww  .j a va 2 s  .c  om
    {
        if (!retrieveSource)
            generator.writeBooleanField("_source", false);
        if (explain)
            generator.writeBooleanField("explain", true);
        if (!disablePaging) {
            generator.writeNumberField("from", start);
            generator.writeNumberField("size", limit);
        }
        if (timeoutSeconds > 0) {
            generator.writeNumberField("timeout", timeoutSeconds * 1000);
        }
        if (sortField != null)
            generateSort(generator);
        if (fields != null && fields.size() > 0)
            generateFields(generator);
        if (query != null) {
            generator.writeFieldName("query");
            query.generate(generator);
        }

        if (sort != null) {
            sort.generate(generator);
        }

        if (aggregations != null && aggregations.size() > 0) {
            generator.writeObjectFieldStart(Aggregation.AGGREGATION_OBJECT_NAME);
            for (Aggregation aggregation : aggregations) {
                aggregation.generate(generator);
            }
            generator.writeEndObject();
        }
    }
    generator.writeEndObject();
}

From source file:net.opentsdb.tsd.HttpSampleSerializer.java

/**
 * Format the results from a timeseries data query
 * @param data_query The TSQuery object used to fetch the results
 * @param results The data fetched from storage
 * @param globals An optional list of global annotation objects
 * @return A ChannelBuffer object to pass on to the caller
 */// w  w  w  . j  a  va2s . c  om
public ChannelBuffer formatQueryV1(final TSQuery data_query, final List<DataPoints[]> results,
        final List<Annotation> globals) {

    final boolean as_arrays = this.query.hasQueryStringParam("arrays");
    final String jsonp = this.query.getQueryStringParam("jsonp");

    // todo - this should be streamed at some point since it could be HUGE
    final ChannelBuffer response = ChannelBuffers.dynamicBuffer();
    final OutputStream output = new ChannelBufferOutputStream(response);
    try {
        // don't forget jsonp
        if (jsonp != null && !jsonp.isEmpty()) {
            output.write((jsonp + "(").getBytes(query.getCharset()));
        }
        JsonGenerator json = JSON.getFactory().createGenerator(output);
        json.writeStartArray();

        for (DataPoints[] separate_dps : results) {
            for (DataPoints dps : separate_dps) {
                json.writeStartObject();

                json.writeStringField("metric", dps.metricName());

                json.writeFieldName("tags");
                json.writeStartObject();
                if (dps.getTags() != null) {
                    for (Map.Entry<String, String> tag : dps.getTags().entrySet()) {
                        json.writeStringField(tag.getKey(), tag.getValue());
                    }
                }
                json.writeEndObject();

                json.writeFieldName("aggregateTags");
                json.writeStartArray();
                if (dps.getAggregatedTags() != null) {
                    for (String atag : dps.getAggregatedTags()) {
                        json.writeString(atag);
                    }
                }
                json.writeEndArray();

                if (data_query.getShowTSUIDs()) {
                    json.writeFieldName("tsuids");
                    json.writeStartArray();
                    final List<String> tsuids = dps.getTSUIDs();
                    Collections.sort(tsuids);
                    for (String tsuid : tsuids) {
                        json.writeString(tsuid);
                    }
                    json.writeEndArray();
                }

                if (!data_query.getNoAnnotations()) {
                    final List<Annotation> annotations = dps.getAnnotations();
                    if (annotations != null) {
                        Collections.sort(annotations);
                        json.writeArrayFieldStart("annotations");
                        for (Annotation note : annotations) {
                            json.writeObject(note);
                        }
                        json.writeEndArray();
                    }

                    if (globals != null && !globals.isEmpty()) {
                        Collections.sort(globals);
                        json.writeArrayFieldStart("globalAnnotations");
                        for (Annotation note : globals) {
                            json.writeObject(note);
                        }
                        json.writeEndArray();
                    }
                }

                // now the fun stuff, dump the data
                json.writeFieldName("dps");

                // default is to write a map, otherwise write arrays
                if (as_arrays) {
                    json.writeStartArray();
                    for (final DataPoint dp : dps) {
                        if (dp.timestamp() < data_query.startTime() || dp.timestamp() > data_query.endTime()) {
                            continue;
                        }
                        final long timestamp = data_query.getMsResolution() ? dp.timestamp()
                                : dp.timestamp() / 1000;
                        json.writeStartArray();
                        json.writeNumber(timestamp);
                        json.writeNumber(dp.isInteger() ? dp.longValue() : dp.doubleValue());
                        json.writeEndArray();
                    }
                    json.writeEndArray();
                } else {
                    json.writeStartObject();
                    for (final DataPoint dp : dps) {
                        if (dp.timestamp() < (data_query.startTime())
                                || dp.timestamp() > (data_query.endTime())) {
                            continue;
                        }
                        final long timestamp = data_query.getMsResolution() ? dp.timestamp()
                                : dp.timestamp() / 1000;
                        json.writeNumberField(Long.toString(timestamp),
                                dp.isInteger() ? dp.longValue() : dp.doubleValue());
                    }
                    json.writeEndObject();
                }

                // close the results for this particular query
                json.writeEndObject();
            }
        }

        // close
        json.writeEndArray();
        json.close();

        if (jsonp != null && !jsonp.isEmpty()) {
            output.write(")".getBytes());
        }
        return response;
    } catch (IOException e) {
        LOG.error("Unexpected exception", e);
        throw new RuntimeException(e);
    }
}

From source file:org.talend.dataprep.schema.xls.serialization.XlsRunnable.java

private void serializeColumns(Workbook workbook, JsonGenerator generator, Sheet sheet,
        List<ColumnMetadata> columns) throws IOException {

    for (int i = 0, size = sheet.getLastRowNum(); i <= size; i++) {
        if (limit > 0 && i > limit) {
            break;
        }//from  w w  w. j av a  2 s  .  c om
        // is header line?
        Row row = sheet.getRow(i);
        if (isHeaderLine(i, columns) || row == null) {
            continue;
        }

        generator.writeStartObject();
        for (ColumnMetadata columnMetadata : columns) {

            // do not write the values if this has been detected as an header
            if (i < columnMetadata.getHeaderSize()) {
                continue;
            }

            int colId = Integer.parseInt(columnMetadata.getId());
            String cellValue = getCellValueAsString(row.getCell(colId),
                    workbook.getCreationHelper().createFormulaEvaluator());
            LOG.trace("cellValue for {}/{}: {}", i, colId, cellValue);
            generator.writeFieldName(columnMetadata.getId());
            if (cellValue != null) {
                generator.writeString(cellValue);
            } else {
                generator.writeNull();
            }
        }
        generator.writeEndObject();
    }
}

From source file:ijfx.service.overlay.io.OverlaySerializer.java

private void saveRectangleOverlay(RectangleOverlay rectangleOverlay, JsonGenerator jg) throws IOException {
    jg.writeStartObject();/*from w  w w.  j a v  a2s  .c  om*/
    jg.writeStringField(JsonOverlayToken.OVERLAY_TYPE, JsonOverlayToken.RECTANGLE_OVERLAY);
    int dimensionCount = rectangleOverlay.numDimensions();

    Double[] origin = Utils.extractArray(rectangleOverlay::getOrigin, dimensionCount);
    Double[] extent = Utils.extractArray(rectangleOverlay::getExtent, dimensionCount);

    ColorRGB fcolor = rectangleOverlay.getFillColor();
    ColorRGB lcolor = rectangleOverlay.getLineColor();

    Integer[] fill_color = { fcolor.getRed(), fcolor.getGreen(), fcolor.getBlue() };
    Integer[] line_color = { lcolor.getRed(), lcolor.getGreen(), lcolor.getBlue() };

    double width = rectangleOverlay.getLineWidth();

    writeNumberArray(jg, JsonOverlayToken.ORIGIN, origin);
    writeNumberArray(jg, JsonOverlayToken.EXTENT, extent);

    writeNumberArray(jg, JsonOverlayToken.FILL_COLOR, fill_color);
    writeNumberArray(jg, JsonOverlayToken.LINE_COLOR, line_color);

    jg.writeFieldName(JsonOverlayToken.LINE_WIDTH);
    jg.writeNumber(width);

    jg.writeEndObject();

}

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

protected void writeNativeFields(Native nativ, JsonGenerator gen) throws IOException {
    switch (nativ.getRequestOneofCase()) {
    case REQUEST_NATIVE:
        gen.writeFieldName("request");
        if (factory().isForceNativeAsObject()) {
            nativeWriter().writeNativeRequest(nativ.getRequestNative(), gen);
        } else {//from w  w w.  ja  va 2  s.  c o  m
            gen.writeString(nativeWriter().writeNativeRequest(nativ.getRequestNative()));
        }
        break;
    case REQUEST:
        gen.writeStringField("request", nativ.getRequest());
        break;
    case REQUESTONEOF_NOT_SET:
        checkRequired(false);
    }
    if (nativ.hasVer()) {
        gen.writeStringField("ver", nativ.getVer());
    }
    writeEnums("api", nativ.getApiList(), gen);
    writeEnums("battr", nativ.getBattrList(), gen);
}

From source file:be.dnsbelgium.rdap.jackson.ContactSerializer.java

@Override
public void serialize(Contact contact, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
        throws IOException {
    jsonGenerator.writeStartArray();/*from   w  w  w.  j av a  2 s  . c om*/
    // start write version
    jsonGenerator.writeStartArray();
    jsonGenerator.writeString("version");
    jsonGenerator.writeStartObject();
    jsonGenerator.writeEndObject();
    jsonGenerator.writeString("text");
    jsonGenerator.writeString("4.0");
    jsonGenerator.writeEndArray();
    // end write version
    for (Contact.Property property : contact.getProperties()) {
        // start write property
        jsonGenerator.writeStartArray();
        // start write property name
        String key = (property.getGroup() == null) ? property.getName()
                : property.getGroup() + "." + property.getName();
        jsonGenerator.writeString(property.getName().toLowerCase(Locale.ENGLISH));
        // end write property name
        // start write property parameters
        jsonGenerator.writeStartObject();
        if (property.getGroup() != null) {
            jsonGenerator.writeFieldName("group");
            jsonGenerator.writeString(property.getGroup());
        }
        if (property.getParameters() != null) {

            Iterator<String> it = property.getParameters().keys();
            while (it.hasNext()) {
                String k = it.next();
                if (k.equalsIgnoreCase("value")) {
                    continue;
                }
                Set<String> values = property.getParameters().get(k);
                if (values.size() == 0) {
                    // no parameters for this property, skip this step
                    continue;
                }
                jsonGenerator.writeFieldName(k.toLowerCase(Locale.ENGLISH));
                if (values.size() == 1) {
                    jsonGenerator.writeString(values.toArray(new String[values.size()])[0]);
                    continue;
                }
                // start write all property parameter values (array)
                jsonGenerator.writeStartArray();
                for (String str : property.getParameters().get(k)) {
                    jsonGenerator.writeString(str);
                }
                jsonGenerator.writeEndArray();
                // end write all property parameter values (array)

            }
        }
        jsonGenerator.writeEndObject();
        // end write property parameters
        // start write property type
        String value = "text";
        if (property.getParameters() != null) {
            Set<String> types = property.getParameters().get("VALUE");
            if (types != null) {
                value = types.iterator().next();
            }
        }
        jsonGenerator.writeString(value);
        // end write property type
        // start write property value
        JsonSerializer s = serializerProvider.findValueSerializer(property.getValue().getClass(), null);
        s.serialize(property.getValue(), jsonGenerator, serializerProvider);
        // end write property value
        jsonGenerator.writeEndArray();
        // end write property
    }
    jsonGenerator.writeEndArray();
}

From source file:org.apache.olingo.client.core.serialization.JsonPropertySerializer.java

protected void doContainerSerialize(final ResWrap<Property> container, final JsonGenerator jgen)
        throws IOException, EdmPrimitiveTypeException {

    final Property property = container.getPayload();

    jgen.writeStartObject();//  www.ja v a2s . c  o m

    if (serverMode && container.getContextURL() != null) {
        jgen.writeStringField(Constants.JSON_CONTEXT, container.getContextURL().toASCIIString());
    }

    if (StringUtils.isNotBlank(property.getType())) {
        jgen.writeStringField(Constants.JSON_TYPE,
                new EdmTypeInfo.Builder().setTypeExpression(property.getType()).build().external());
    }

    for (Annotation annotation : property.getAnnotations()) {
        valuable(jgen, annotation, "@" + annotation.getTerm());
    }

    if (property.isNull()) {
        jgen.writeBooleanField(Constants.JSON_NULL, true);
    } else if (property.isGeospatial() || property.isCollection()) {
        valuable(jgen, property, Constants.VALUE);
    } else if (property.isPrimitive()) {
        final EdmTypeInfo typeInfo = property.getType() == null ? null
                : new EdmTypeInfo.Builder().setTypeExpression(property.getType()).build();

        jgen.writeFieldName(Constants.VALUE);
        primitiveValue(jgen, typeInfo, property.asPrimitive());
    } else if (property.isEnum()) {
        jgen.writeStringField(Constants.VALUE, property.asEnum().toString());
    } else if (property.isComplex()) {
        for (Property cproperty : property.asComplex().getValue()) {
            valuable(jgen, cproperty, cproperty.getName());
        }
    } else if (property.isComplex()) {
        for (Property cproperty : property.asComplex().getValue()) {
            valuable(jgen, cproperty, cproperty.getName());
        }
    }

    jgen.writeEndObject();
}

From source file:net.opentsdb.tsd.HttpJsonSerializer.java

/**
 * Format the results from a timeseries data query
 * @param data_query The TSQuery object used to fetch the results
 * @param results The data fetched from storage
 * @param globals An optional list of global annotation objects
 * @return A ChannelBuffer object to pass on to the caller
 *//*from w  w  w.jav  a 2  s. c o  m*/
public ChannelBuffer formatQueryV1(final TSQuery data_query, final List<DataPoints[]> results,
        final List<Annotation> globals) {

    final boolean as_arrays = this.query.hasQueryStringParam("arrays");
    final String jsonp = this.query.getQueryStringParam("jsonp");

    // todo - this should be streamed at some point since it could be HUGE
    final ChannelBuffer response = ChannelBuffers.dynamicBuffer();
    final OutputStream output = new ChannelBufferOutputStream(response);
    try {
        // don't forget jsonp
        if (jsonp != null && !jsonp.isEmpty()) {
            output.write((jsonp + "(").getBytes(query.getCharset()));
        }
        JsonGenerator json = JSON.getFactory().createGenerator(output);
        json.writeStartArray();

        for (DataPoints[] separate_dps : results) {
            for (DataPoints dps : separate_dps) {
                json.writeStartObject();

                json.writeStringField("metric", dps.metricName());

                json.writeFieldName("tags");
                json.writeStartObject();
                if (dps.getTags() != null) {
                    for (Map.Entry<String, String> tag : dps.getTags().entrySet()) {
                        json.writeStringField(tag.getKey(), tag.getValue());
                    }
                }
                json.writeEndObject();

                json.writeFieldName("aggregateTags");
                json.writeStartArray();
                if (dps.getAggregatedTags() != null) {
                    for (String atag : dps.getAggregatedTags()) {
                        json.writeString(atag);
                    }
                }
                json.writeEndArray();

                if (data_query.getShowTSUIDs()) {
                    json.writeFieldName("tsuids");
                    json.writeStartArray();
                    final List<String> tsuids = dps.getTSUIDs();
                    Collections.sort(tsuids);
                    for (String tsuid : tsuids) {
                        json.writeString(tsuid);
                    }
                    json.writeEndArray();
                }

                if (!data_query.getNoAnnotations()) {
                    final List<Annotation> annotations = dps.getAnnotations();
                    if (annotations != null) {
                        Collections.sort(annotations);
                        json.writeArrayFieldStart("annotations");
                        for (Annotation note : annotations) {
                            json.writeObject(note);
                        }
                        json.writeEndArray();
                    }

                    if (globals != null && !globals.isEmpty()) {
                        Collections.sort(globals);
                        json.writeArrayFieldStart("globalAnnotations");
                        for (Annotation note : globals) {
                            json.writeObject(note);
                        }
                        json.writeEndArray();
                    }
                }

                // now the fun stuff, dump the data
                json.writeFieldName("dps");

                // default is to write a map, otherwise write arrays
                if (as_arrays) {
                    json.writeStartArray();
                    for (final DataPoint dp : dps) {
                        if (dp.timestamp() < data_query.startTime() || dp.timestamp() > data_query.endTime()) {
                            continue;
                        }
                        final long timestamp = data_query.getMsResolution() ? dp.timestamp()
                                : dp.timestamp() / 1000;
                        json.writeStartArray();
                        json.writeNumber(timestamp);
                        if (dp.isInteger()) {
                            json.writeNumber(dp.longValue());
                        } else {
                            json.writeNumber(dp.doubleValue());
                        }
                        json.writeEndArray();
                    }
                    json.writeEndArray();
                } else {
                    json.writeStartObject();
                    for (final DataPoint dp : dps) {
                        if (dp.timestamp() < (data_query.startTime())
                                || dp.timestamp() > (data_query.endTime())) {
                            continue;
                        }
                        final long timestamp = data_query.getMsResolution() ? dp.timestamp()
                                : dp.timestamp() / 1000;
                        if (dp.isInteger()) {
                            json.writeNumberField(Long.toString(timestamp), dp.longValue());
                        } else {
                            json.writeNumberField(Long.toString(timestamp), dp.doubleValue());
                        }
                    }
                    json.writeEndObject();
                }

                // close the results for this particular query
                json.writeEndObject();
            }
        }

        // close
        json.writeEndArray();
        json.close();

        if (jsonp != null && !jsonp.isEmpty()) {
            output.write(")".getBytes());
        }
        return response;
    } catch (IOException e) {
        LOG.error("Unexpected exception", e);
        throw new RuntimeException(e);
    }
}