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

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

Introduction

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

Prototype

public abstract void writeStartObject() throws IOException, JsonGenerationException;

Source Link

Document

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

Usage

From source file:io.pdef.json.JsonJacksonFormat.java

private <T extends Message> void writeMessage(@Nonnull final T object, final JsonGenerator generator)
        throws IOException {
    // Mind polymorphic messages.
    @SuppressWarnings("unchecked")
    MessageDescriptor<T> polymorphic = (MessageDescriptor<T>) object.descriptor();

    generator.writeStartObject();
    for (FieldDescriptor<? super T, ?> field : polymorphic.getFields()) {
        writeMessageField(field, object, generator);
    }//w  w w.  j ava  2  s.  c om
    generator.writeEndObject();
}

From source file:net.solarnetwork.web.support.JSONView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    PropertyEditorRegistrar registrar = this.propertyEditorRegistrar;
    Enumeration<String> attrEnum = request.getAttributeNames();
    while (attrEnum.hasMoreElements()) {
        String key = attrEnum.nextElement();
        Object val = request.getAttribute(key);
        if (val instanceof PropertyEditorRegistrar) {
            registrar = (PropertyEditorRegistrar) val;
            break;
        }//w  w w . ja v  a  2 s .  co  m
    }

    response.setCharacterEncoding(UTF8_CHAR_ENCODING);
    response.setContentType(getContentType());
    Writer writer = response.getWriter();
    if (this.includeParentheses) {
        writer.write('(');
    }
    JsonGenerator json = new JsonFactory().createGenerator(writer);
    json.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    if (indentAmount > 0) {
        json.useDefaultPrettyPrinter();
    }
    json.writeStartObject();
    for (String key : model.keySet()) {
        Object val = model.get(key);
        writeJsonValue(json, key, val, registrar);
    }
    json.writeEndObject();
    json.close();
    if (this.includeParentheses) {
        writer.write(')');
    }
}

From source file:org.n52.tamis.core.json.serialize.processes.execute.ExecuteOutputSerializer.java

@Override
public void serialize(ExecuteOutput output_simple, JsonGenerator jsonGenerator, SerializerProvider serProvider)
        throws IOException, JsonProcessingException {

    logger.info("Start serialization of output \"{}\"", output_simple);

    /*/*ww  w. ja  v  a  2 s . c o  m*/
     * write the input as WPS "Data" element
     * 
     * expected structure looks like:
     * 
     *    {
          "_mimeType": "text/xml",
          "_id": "complexOutput",
          "_transmission": "reference"
      }
     */

    jsonGenerator.writeStartObject();

    jsonGenerator.writeStringField("_mimeType", output_simple.getType());

    jsonGenerator.writeStringField("_id", output_simple.getId());

    jsonGenerator.writeStringField("_transmission", output_simple.getTransmission());

    jsonGenerator.writeEndObject();

    logger.info("serialization of output ended.");
}

From source file:com.neoteric.starter.metrics.report.elastic.ElasticsearchReporter.java

private void checkForIndexTemplate() {
    try {// w  w  w .  j  a  va 2 s  . c om
        HttpURLConnection connection = openConnection("/_template/metrics_template", "HEAD");
        connection.disconnect();
        boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND;

        // nothing there, lets create it
        if (isTemplateMissing) {
            LOGGER.debug("No metrics template found in elasticsearch. Adding...");
            HttpURLConnection putTemplateConnection = openConnection("/_template/metrics_template", "PUT");
            JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream());
            json.writeStartObject();
            json.writeStringField("template", index + "*");
            json.writeObjectFieldStart("mappings");

            json.writeObjectFieldStart("_default_");
            json.writeObjectFieldStart("_all");
            json.writeBooleanField("enabled", false);
            json.writeEndObject();
            json.writeObjectFieldStart("properties");
            json.writeObjectFieldStart("name");
            json.writeObjectField("type", "string");
            json.writeObjectField("index", "not_analyzed");
            json.writeEndObject();
            json.writeEndObject();
            json.writeEndObject();

            json.writeEndObject();
            json.writeEndObject();
            json.flush();

            putTemplateConnection.disconnect();
            if (putTemplateConnection.getResponseCode() != HttpStatus.OK.value()) {
                LOGGER.error(
                        "Error adding metrics template to elasticsearch: {}/{}"
                                + putTemplateConnection.getResponseCode(),
                        putTemplateConnection.getResponseMessage());
            }
        }
        checkedForIndexTemplate = true;
    } catch (IOException e) {
        LOGGER.error("Error when checking/adding metrics template to elasticsearch", e);
    }
}

From source file:org.springframework.cloud.netflix.hystrix.amqp.HystrixStreamTask.java

@Scheduled(fixedRateString = "${hystrix.stream.amqp.gatherRate:500}")
public void gatherMetrics() {
    try {/*from w  ww.ja v a 2s.  c  o  m*/
        // command metrics
        Collection<HystrixCommandMetrics> instances = HystrixCommandMetrics.getInstances();
        if (!instances.isEmpty()) {
            log.trace("gathering metrics size: " + instances.size());
        }

        ServiceInstance localService = this.discoveryClient.getLocalServiceInstance();

        for (HystrixCommandMetrics commandMetrics : instances) {
            HystrixCommandKey key = commandMetrics.getCommandKey();
            HystrixCircuitBreaker circuitBreaker = HystrixCircuitBreaker.Factory.getInstance(key);

            StringWriter jsonString = new StringWriter();
            JsonGenerator json = this.jsonFactory.createGenerator(jsonString);

            json.writeStartObject();

            addServiceData(json, localService);
            json.writeObjectFieldStart("data");
            json.writeStringField("type", "HystrixCommand");
            String name = key.name();

            if (this.properties.isPrefixMetricName()) {
                name = localService.getServiceId() + "." + name;
            }

            json.writeStringField("name", name);
            json.writeStringField("group", commandMetrics.getCommandGroup().name());
            json.writeNumberField("currentTime", System.currentTimeMillis());

            // circuit breaker
            if (circuitBreaker == null) {
                // circuit breaker is disabled and thus never open
                json.writeBooleanField("isCircuitBreakerOpen", false);
            } else {
                json.writeBooleanField("isCircuitBreakerOpen", circuitBreaker.isOpen());
            }
            HystrixCommandMetrics.HealthCounts healthCounts = commandMetrics.getHealthCounts();
            json.writeNumberField("errorPercentage", healthCounts.getErrorPercentage());
            json.writeNumberField("errorCount", healthCounts.getErrorCount());
            json.writeNumberField("requestCount", healthCounts.getTotalRequests());

            // rolling counters
            json.writeNumberField("rollingCountCollapsedRequests",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.COLLAPSED));
            json.writeNumberField("rollingCountExceptionsThrown",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN));
            json.writeNumberField("rollingCountFailure",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.FAILURE));
            json.writeNumberField("rollingCountFallbackFailure",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE));
            json.writeNumberField("rollingCountFallbackRejection",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION));
            json.writeNumberField("rollingCountFallbackSuccess",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS));
            json.writeNumberField("rollingCountResponsesFromCache",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE));
            json.writeNumberField("rollingCountSemaphoreRejected",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED));
            json.writeNumberField("rollingCountShortCircuited",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED));
            json.writeNumberField("rollingCountSuccess",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS));
            json.writeNumberField("rollingCountThreadPoolRejected",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED));
            json.writeNumberField("rollingCountTimeout",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT));

            json.writeNumberField("currentConcurrentExecutionCount",
                    commandMetrics.getCurrentConcurrentExecutionCount());

            // latency percentiles
            json.writeNumberField("latencyExecute_mean", commandMetrics.getExecutionTimeMean());
            json.writeObjectFieldStart("latencyExecute");
            json.writeNumberField("0", commandMetrics.getExecutionTimePercentile(0));
            json.writeNumberField("25", commandMetrics.getExecutionTimePercentile(25));
            json.writeNumberField("50", commandMetrics.getExecutionTimePercentile(50));
            json.writeNumberField("75", commandMetrics.getExecutionTimePercentile(75));
            json.writeNumberField("90", commandMetrics.getExecutionTimePercentile(90));
            json.writeNumberField("95", commandMetrics.getExecutionTimePercentile(95));
            json.writeNumberField("99", commandMetrics.getExecutionTimePercentile(99));
            json.writeNumberField("99.5", commandMetrics.getExecutionTimePercentile(99.5));
            json.writeNumberField("100", commandMetrics.getExecutionTimePercentile(100));
            json.writeEndObject();
            //
            json.writeNumberField("latencyTotal_mean", commandMetrics.getTotalTimeMean());
            json.writeObjectFieldStart("latencyTotal");
            json.writeNumberField("0", commandMetrics.getTotalTimePercentile(0));
            json.writeNumberField("25", commandMetrics.getTotalTimePercentile(25));
            json.writeNumberField("50", commandMetrics.getTotalTimePercentile(50));
            json.writeNumberField("75", commandMetrics.getTotalTimePercentile(75));
            json.writeNumberField("90", commandMetrics.getTotalTimePercentile(90));
            json.writeNumberField("95", commandMetrics.getTotalTimePercentile(95));
            json.writeNumberField("99", commandMetrics.getTotalTimePercentile(99));
            json.writeNumberField("99.5", commandMetrics.getTotalTimePercentile(99.5));
            json.writeNumberField("100", commandMetrics.getTotalTimePercentile(100));
            json.writeEndObject();

            // property values for reporting what is actually seen by the command
            // rather than what was set somewhere
            HystrixCommandProperties commandProperties = commandMetrics.getProperties();

            json.writeNumberField("propertyValue_circuitBreakerRequestVolumeThreshold",
                    commandProperties.circuitBreakerRequestVolumeThreshold().get());
            json.writeNumberField("propertyValue_circuitBreakerSleepWindowInMilliseconds",
                    commandProperties.circuitBreakerSleepWindowInMilliseconds().get());
            json.writeNumberField("propertyValue_circuitBreakerErrorThresholdPercentage",
                    commandProperties.circuitBreakerErrorThresholdPercentage().get());
            json.writeBooleanField("propertyValue_circuitBreakerForceOpen",
                    commandProperties.circuitBreakerForceOpen().get());
            json.writeBooleanField("propertyValue_circuitBreakerForceClosed",
                    commandProperties.circuitBreakerForceClosed().get());
            json.writeBooleanField("propertyValue_circuitBreakerEnabled",
                    commandProperties.circuitBreakerEnabled().get());

            json.writeStringField("propertyValue_executionIsolationStrategy",
                    commandProperties.executionIsolationStrategy().get().name());
            json.writeNumberField("propertyValue_executionIsolationThreadTimeoutInMilliseconds",
                    commandProperties.executionIsolationThreadTimeoutInMilliseconds().get());
            json.writeBooleanField("propertyValue_executionIsolationThreadInterruptOnTimeout",
                    commandProperties.executionIsolationThreadInterruptOnTimeout().get());
            json.writeStringField("propertyValue_executionIsolationThreadPoolKeyOverride",
                    commandProperties.executionIsolationThreadPoolKeyOverride().get());
            json.writeNumberField("propertyValue_executionIsolationSemaphoreMaxConcurrentRequests",
                    commandProperties.executionIsolationSemaphoreMaxConcurrentRequests().get());
            json.writeNumberField("propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests",
                    commandProperties.fallbackIsolationSemaphoreMaxConcurrentRequests().get());

            // TODO
            /*
             * The following are commented out as these rarely change and are verbose
             * for streaming for something people don't change. We could perhaps allow
             * a property or request argument to include these.
             */

            // json.put("propertyValue_metricsRollingPercentileEnabled",
            // commandProperties.metricsRollingPercentileEnabled().get());
            // json.put("propertyValue_metricsRollingPercentileBucketSize",
            // commandProperties.metricsRollingPercentileBucketSize().get());
            // json.put("propertyValue_metricsRollingPercentileWindow",
            // commandProperties.metricsRollingPercentileWindowInMilliseconds().get());
            // json.put("propertyValue_metricsRollingPercentileWindowBuckets",
            // commandProperties.metricsRollingPercentileWindowBuckets().get());
            // json.put("propertyValue_metricsRollingStatisticalWindowBuckets",
            // commandProperties.metricsRollingStatisticalWindowBuckets().get());
            json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds",
                    commandProperties.metricsRollingStatisticalWindowInMilliseconds().get());

            json.writeBooleanField("propertyValue_requestCacheEnabled",
                    commandProperties.requestCacheEnabled().get());
            json.writeBooleanField("propertyValue_requestLogEnabled",
                    commandProperties.requestLogEnabled().get());

            json.writeNumberField("reportingHosts", 1); // this will get summed across
            // all instances in a cluster

            json.writeEndObject(); // end data attribute
            json.writeEndObject();
            json.close();

            // output
            this.jsonMetrics.add(jsonString.getBuffer().toString());
        }

        // thread pool metrics
        for (HystrixThreadPoolMetrics threadPoolMetrics : HystrixThreadPoolMetrics.getInstances()) {
            HystrixThreadPoolKey key = threadPoolMetrics.getThreadPoolKey();

            StringWriter jsonString = new StringWriter();
            JsonGenerator json = this.jsonFactory.createGenerator(jsonString);
            json.writeStartObject();

            addServiceData(json, localService);
            json.writeObjectFieldStart("data");

            json.writeStringField("type", "HystrixThreadPool");
            json.writeStringField("name", key.name());
            json.writeNumberField("currentTime", System.currentTimeMillis());

            json.writeNumberField("currentActiveCount", threadPoolMetrics.getCurrentActiveCount().intValue());
            json.writeNumberField("currentCompletedTaskCount",
                    threadPoolMetrics.getCurrentCompletedTaskCount().longValue());
            json.writeNumberField("currentCorePoolSize", threadPoolMetrics.getCurrentCorePoolSize().intValue());
            json.writeNumberField("currentLargestPoolSize",
                    threadPoolMetrics.getCurrentLargestPoolSize().intValue());
            json.writeNumberField("currentMaximumPoolSize",
                    threadPoolMetrics.getCurrentMaximumPoolSize().intValue());
            json.writeNumberField("currentPoolSize", threadPoolMetrics.getCurrentPoolSize().intValue());
            json.writeNumberField("currentQueueSize", threadPoolMetrics.getCurrentQueueSize().intValue());
            json.writeNumberField("currentTaskCount", threadPoolMetrics.getCurrentTaskCount().longValue());
            json.writeNumberField("rollingCountThreadsExecuted",
                    threadPoolMetrics.getRollingCountThreadsExecuted());
            json.writeNumberField("rollingMaxActiveThreads", threadPoolMetrics.getRollingMaxActiveThreads());

            json.writeNumberField("propertyValue_queueSizeRejectionThreshold",
                    threadPoolMetrics.getProperties().queueSizeRejectionThreshold().get());
            json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds",
                    threadPoolMetrics.getProperties().metricsRollingStatisticalWindowInMilliseconds().get());

            json.writeNumberField("reportingHosts", 1); // this will get summed across
            // all instances in a cluster

            json.writeEndObject(); // end of data object
            json.writeEndObject();
            json.close();
            // output to stream
            this.jsonMetrics.add(jsonString.getBuffer().toString());
        }
    } catch (Exception ex) {
        log.error("Error adding metrics to queue", ex);
    }
}

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

/**
 * Writes a formatted exception to the given writer.
 *
 * @param message   the log message//from  ww  w.  j a  v a2 s .c  o  m
 * @param throwable the exception
 * @param level     the error level
 * @param out       the destination
 * @throws IOException if there are IO errors in the destination
 */
void writeFormattedException(final String message, final Throwable throwable, final Level level,
        final Writer out) throws IOException {
    JsonGenerator generator = new JsonFactory().createJsonGenerator(out);

    Throwable rootThrowable = throwable;
    while (this.passthroughExceptions.contains(rootThrowable.getClass()) && rootThrowable.getCause() != null) {
        rootThrowable = rootThrowable.getCause();
    }

    generator.writeStartObject();
    generator.writeStringField("project", this.project);
    generator.writeStringField("environment", this.environment);
    generator.writeStringField("serverName", this.serverName);
    generator.writeStringField("backtrace", ExceptionUtils.getStackTrace(throwable));
    generator.writeStringField("message", rootThrowable.getMessage());
    generator.writeStringField("logMessage", message);
    generator.writeStringField("type", rootThrowable.getClass().getName());
    if (level != Level.ERROR) {
        generator.writeStringField("errorLevel", level.toString());
    }
    writeContext(generator);
    generator.writeEndObject();
    generator.close();
}

From source file:com.strategicgains.hyperexpress.serialization.siren.jackson.SirenResourceSerializer.java

private void writeEntities(Resource resource, JsonGenerator jgen) throws JsonGenerationException, IOException {
    Map<String, List<Resource>> entities = resource.getResources();

    if (entities == null || entities.isEmpty())
        return;/*from   ww  w . j a  v  a 2  s .com*/

    jgen.writeArrayFieldStart(ENTITIES);

    for (Entry<String, List<Resource>> entry : entities.entrySet()) {
        for (Resource r : entry.getValue()) {
            jgen.writeStartObject();
            jgen.writeArrayFieldStart("rel");
            jgen.writeString(entry.getKey());
            jgen.writeEndArray();
            renderJson((SirenResource) r, jgen);
            jgen.writeEndObject();
        }
    }

    jgen.writeEndArray();
}

From source file:org.springframework.cloud.netflix.metrics.atlas.AtlasMetricObserver.java

private int writeMetrics(JsonGenerator gen, List<Metric> metrics) throws IOException {
    int totalMetricsInBatch = 0;
    gen.writeArrayFieldStart("metrics");

    for (Metric m : metrics) {
        if (!validTags(m.getConfig().getTags()))
            continue;

        if (!Number.class.isAssignableFrom(m.getValue().getClass()))
            continue;

        gen.writeStartObject();// www .ja va2  s. co m

        gen.writeObjectFieldStart("tags");
        gen.writeStringField("name", m.getConfig().getName());
        for (Tag tag : m.getConfig().getTags())
            gen.writeStringField(tag.getKey(), tag.getValue());
        gen.writeEndObject();

        gen.writeNumberField("start", m.getTimestamp());
        gen.writeNumberField("value", m.getNumberValue().doubleValue());

        gen.writeEndObject();

        totalMetricsInBatch++;
    }

    gen.writeEndArray();
    return totalMetricsInBatch;
}

From source file:org.emfjson.jackson.streaming.StreamWriter.java

public void generate(final JsonGenerator generator, final EObject object) throws IOException {
    prepare(generator, object.eResource());

    final EClass eClass = object.eClass();
    final List<EAttribute> attributes = cache.getAttributes(eClass);
    final List<EReference> references = cache.getReferences(eClass);

    generator.writeStartObject();

    if (options.serializeTypes) {
        generator.writeStringField(EJS_TYPE_KEYWORD, cache.getHref(null, eClass));
    }/*from w w  w .j a  va2 s. c o m*/

    if (object.eResource() instanceof UuidResource) {
        String id = ((UuidResource) object.eResource()).getID(object);
        if (id != null) {
            generator.writeStringField(EJS_UUID_ANNOTATION, id);
        }
    } else {
        if (options.useId) {
            String id = object.eResource().getURIFragment(object);
            if (id != null) {
                generator.writeStringField(EJS_UUID_ANNOTATION, id);
            }
        }
    }

    for (final EAttribute attribute : attributes) {
        if (isCandidate(object, attribute)) {
            final String key = cache.getKey(attribute);
            final Object value = object.eGet(attribute);

            if (isFeatureMap(attribute)) {
                serializeFeatureMap(generator, attribute, object);
            } else {
                values.serialize(generator, key, attribute, value);
            }
        }
    }

    for (final EReference reference : references) {
        if (isCandidate(object, reference)) {
            final Object value = object.eGet(reference);
            final String key = cache.getKey(reference);

            if (isMapEntry(reference.getEReferenceType())) {
                serializeMapEntry(generator, key, reference, value);
            } else if (!reference.isContainment()) {
                referenceWriter.serialize(generator, key, reference, value);
            } else {
                serializeContainment(generator, key, reference, object, value);
            }
        }
    }

    generator.writeEndObject();
}

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

/**
 * Take query results, make a JSON String
 * //from  w  w w .  j  a va 2 s .  co  m
 * @param results List of Result objects
 * @return a String containing a JSON message, or null if there are no values to report
 * 
 * @throws IOException if there is some problem generating the JSON, should be uncommon
 */
private String getGatewayMessage(final List<Result> results) throws IOException {
    int valueCount = 0;
    Writer writer = new StringWriter();
    JsonGenerator g = jsonFactory.createGenerator(writer);
    g.writeStartObject();
    g.writeNumberField("timestamp", System.currentTimeMillis() / 1000);
    g.writeNumberField("proto_version", STACKDRIVER_PROTOCOL_VERSION);
    g.writeArrayFieldStart("data");

    List<String> typeNames = this.getTypeNames();

    for (Result metric : results) {
        Map<String, Object> values = metric.getValues();
        if (values != null) {
            for (Entry<String, Object> entry : values.entrySet()) {
                if (isNumeric(entry.getValue())) {
                    // we have a numeric value, write a value into the message

                    StringBuilder nameBuilder = new StringBuilder();

                    // put the prefix if set
                    if (this.prefix != null) {
                        nameBuilder.append(prefix);
                        nameBuilder.append(".");
                    }

                    // put the class name or its alias if available
                    if (!metric.getKeyAlias().isEmpty()) {
                        nameBuilder.append(metric.getKeyAlias());

                    } else {
                        nameBuilder.append(metric.getClassName());
                    }

                    // Wildcard "typeNames" substitution
                    String typeName = com.googlecode.jmxtrans.model.naming.StringUtils
                            .cleanupStr(TypeNameValuesStringBuilder.getDefaultBuilder().build(typeNames,
                                    metric.getTypeName()));
                    if (typeName != null && typeName.length() > 0) {
                        nameBuilder.append(".");
                        nameBuilder.append(typeName);
                    }

                    // add the attribute name
                    nameBuilder.append(".");
                    nameBuilder.append(metric.getAttributeName());

                    // put the value name if it differs from the attribute name
                    if (!entry.getKey().equals(metric.getAttributeName())) {
                        nameBuilder.append(".");
                        nameBuilder.append(entry.getKey());
                    }

                    // check for Float/Double NaN since these will cause the message validation to fail 
                    if (entry.getValue() instanceof Float && ((Float) entry.getValue()).isNaN()) {
                        logger.info("Metric value for " + nameBuilder.toString() + " is NaN, skipping");
                        continue;
                    }

                    if (entry.getValue() instanceof Double && ((Double) entry.getValue()).isNaN()) {
                        logger.info("Metric value for " + nameBuilder.toString() + " is NaN, skipping");
                        continue;
                    }

                    valueCount++;
                    g.writeStartObject();

                    g.writeStringField("name", nameBuilder.toString());

                    g.writeNumberField("value", Double.valueOf(entry.getValue().toString()));

                    // if the metric is attached to an instance, include that in the message
                    if (instanceId != null && !instanceId.isEmpty()) {
                        g.writeStringField("instance", instanceId);
                    }
                    g.writeNumberField("collected_at", metric.getEpoch() / 1000);
                    g.writeEndObject();
                }
            }
        }
    }

    g.writeEndArray();
    g.writeEndObject();
    g.flush();
    g.close();

    // return the message if there are any values to report
    if (valueCount > 0) {
        return writer.toString();
    } else {
        return null;
    }
}