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

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

Introduction

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

Prototype

public abstract void writeStartArray() throws IOException, JsonGenerationException;

Source Link

Document

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

Usage

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

public static void serialize(final JsonGenerator jgen, final Element node, final String type)
        throws IOException {
    final EdmSimpleType edmSimpleType = EdmSimpleType.fromValue(type);

    if (edmSimpleType.equals(EdmSimpleType.GeographyCollection)
            || edmSimpleType.equals(EdmSimpleType.GeometryCollection)) {

        jgen.writeStringField(ODataConstants.ATTR_TYPE, EdmSimpleType.GeometryCollection.name());
    } else {/*from   ww  w  .  j a va  2  s  .  co  m*/
        final int yIdx = edmSimpleType.name().indexOf('y');
        final String itemType = edmSimpleType.name().substring(yIdx + 1);
        jgen.writeStringField(ODataConstants.ATTR_TYPE, itemType);
    }

    Element root = null;
    switch (edmSimpleType) {
    case GeographyPoint:
    case GeometryPoint:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_POINT).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);
        serializePoint(jgen, XMLUtils.getChildElements(root, ODataConstants.ELEM_POS).get(0));
        jgen.writeEndArray();
        break;

    case GeographyMultiPoint:
    case GeometryMultiPoint:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_MULTIPOINT).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);

        final List<Element> pMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_POINTMEMBERS);
        if (pMembs != null && !pMembs.isEmpty()) {
            for (Element point : XMLUtils.getChildElements(pMembs.get(0), ODataConstants.ELEM_POINT)) {
                jgen.writeStartArray();
                serializePoint(jgen, XMLUtils.getChildElements(point, ODataConstants.ELEM_POS).get(0));
                jgen.writeEndArray();
            }
        }

        jgen.writeEndArray();
        break;

    case GeographyLineString:
    case GeometryLineString:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_LINESTRING).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);
        serializeLineString(jgen, root);
        jgen.writeEndArray();
        break;

    case GeographyMultiLineString:
    case GeometryMultiLineString:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_MULTILINESTRING).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);

        final List<Element> lMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_LINESTRINGMEMBERS);
        if (lMembs != null && !lMembs.isEmpty()) {
            for (Element lineStr : XMLUtils.getChildElements(lMembs.get(0), ODataConstants.ELEM_LINESTRING)) {
                jgen.writeStartArray();
                serializeLineString(jgen, lineStr);
                jgen.writeEndArray();
            }
        }

        jgen.writeEndArray();
        break;

    case GeographyPolygon:
    case GeometryPolygon:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_POLYGON).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);
        serializePolygon(jgen, root);
        jgen.writeEndArray();
        break;

    case GeographyMultiPolygon:
    case GeometryMultiPolygon:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_MULTIPOLYGON).get(0);

        jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES);

        final List<Element> mpMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_SURFACEMEMBERS);
        if (mpMembs != null & !mpMembs.isEmpty()) {
            for (Element pol : XMLUtils.getChildElements(mpMembs.get(0), ODataConstants.ELEM_POLYGON)) {
                jgen.writeStartArray();
                serializePolygon(jgen, pol);
                jgen.writeEndArray();
            }
        }

        jgen.writeEndArray();
        break;

    case GeographyCollection:
    case GeometryCollection:
        root = XMLUtils.getChildElements(node, ODataConstants.ELEM_GEOCOLLECTION).get(0);

        final List<Element> cMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_GEOMEMBERS);
        if (cMembs != null && !cMembs.isEmpty()) {
            jgen.writeArrayFieldStart(ODataConstants.JSON_GEOMETRIES);

            for (Node geom : XMLUtils.getChildNodes(cMembs.get(0), Node.ELEMENT_NODE)) {
                try {
                    final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
                    final Document doc = builder.newDocument();

                    final Element fakeParent = doc.createElementNS(ODataConstants.NS_DATASERVICES,
                            ODataConstants.PREFIX_DATASERVICES + "fake");
                    fakeParent.appendChild(doc.importNode(geom, true));

                    final EdmSimpleType callAsType = XMLUtils.simpleTypeForNode(
                            edmSimpleType == EdmSimpleType.GeographyCollection ? Geospatial.Dimension.GEOGRAPHY
                                    : Geospatial.Dimension.GEOMETRY,
                            geom);

                    jgen.writeStartObject();
                    serialize(jgen, fakeParent, callAsType.toString());
                    jgen.writeEndObject();
                } catch (Exception e) {
                    LOG.warn("While serializing {}", XMLUtils.getSimpleName(geom), e);
                }
            }

            jgen.writeEndArray();
        }
        break;

    default:
    }

    if (root != null) {
        serializeCrs(jgen, root);
    }
}

From source file:com.bazaarvoice.jsonpps.PrettyPrintJson.java

public void prettyPrint(List<File> inputFiles, File outputFile) throws IOException {
    JsonFactory factory = new JsonFactory();
    factory.disable(JsonFactory.Feature.INTERN_FIELD_NAMES);
    if (!strict) {
        factory.enable(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER);
        factory.enable(JsonParser.Feature.ALLOW_COMMENTS);
        factory.enable(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS);
        factory.enable(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS);
        factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
        factory.enable(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS);
        factory.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
    }//from  w ww  .jav  a  2 s .c o  m

    ObjectMapper mapper = null;
    if (sortKeys) {
        mapper = new ObjectMapper(factory);
        mapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
        mapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE);
    }

    // Open the output stream and create the Json emitter.
    JsonGenerator generator;
    File tempOutputFile = null;
    if (STDINOUT.equals(outputFile)) {
        generator = factory.createGenerator(stdout, JsonEncoding.UTF8);
    } else if (!caseInsensitiveContains(inputFiles, outputFile)) {
        generator = factory.createGenerator(outputFile, JsonEncoding.UTF8);
    } else {
        // Writing to an input file.. use a temp file to stage the output until we're done.
        tempOutputFile = getTemporaryFileFor(outputFile);
        generator = factory.createGenerator(tempOutputFile, JsonEncoding.UTF8);
    }
    try {
        // Separate top-level objects by a newline in the output.
        String newline = System.getProperty("line.separator");
        generator.setPrettyPrinter(new DefaultPrettyPrinter(newline));

        if (wrap) {
            generator.writeStartArray();
        }

        for (File inputFile : inputFiles) {
            JsonParser parser;
            if (STDINOUT.equals(inputFile)) {
                parser = factory.createParser(stdin);
            } else {
                parser = factory.createParser(inputFile);
            }
            try {
                while (parser.nextToken() != null) {
                    copyCurrentStructure(parser, mapper, 0, generator);
                }
            } finally {
                parser.close();
            }
        }

        if (wrap) {
            generator.writeEndArray();
        }

        generator.writeRaw(newline);
    } finally {
        generator.close();
    }
    if (tempOutputFile != null && !tempOutputFile.renameTo(outputFile)) {
        System.err.println("error: unable to rename temporary file to output: " + outputFile);
        System.exit(1);
    }
}

From source file:com.baasbox.configuration.PropertiesConfigurationHelper.java

/***
 *
 * Returns a json representation of the Enumerator
 * The Enumerator must implements the IProperties interface
 * @param en    the Enumerator to serialize. It must implements the IProperties interface
 * @return       the representation of the Enumerator 
 *//*from w  w  w.j  av  a  2  s .  co  m*/
@SuppressWarnings("unchecked")
public static String dumpConfigurationAsJson(String section) {
    Class en = CONFIGURATION_SECTIONS.get(section);
    try {
        JsonFactory jfactory = new JsonFactory();
        StringWriter sw = new StringWriter();
        String enumDescription = "";
        JsonGenerator gen = jfactory.createJsonGenerator(sw);

        Method getEnumDescription = en.getMethod("getEnumDescription");
        if (getEnumDescription != null && getEnumDescription.getReturnType() == String.class
                && Modifier.isStatic(getEnumDescription.getModifiers()))
            enumDescription = (String) getEnumDescription.invoke(null);
        gen.writeStartObject(); //{
        gen.writeStringField("section", section); //    "configuration":"EnumName"
        gen.writeStringField("description", enumDescription); //   ,"description": "EnumDescription"
        gen.writeFieldName("sub sections"); //  ,"sections":
        gen.writeStartObject(); //      {
        String lastSection = "";
        EnumSet values = EnumSet.allOf(en);
        for (Object v : values) {
            String key = (String) (en.getMethod("getKey")).invoke(v);
            boolean isVisible = (Boolean) (en.getMethod("isVisible")).invoke(v);
            String valueAsString;
            if (isVisible)
                valueAsString = (String) (en.getMethod("getValueAsString")).invoke(v);
            else
                valueAsString = "--HIDDEN--";
            boolean isEditable = (Boolean) (en.getMethod("isEditable")).invoke(v);
            String valueDescription = (String) (en.getMethod("getValueDescription")).invoke(v);
            Class type = (Class) en.getMethod("getType").invoke(v);
            String subsection = key.substring(0, key.indexOf('.'));
            if (!lastSection.equals(subsection)) {
                if (gen.getOutputContext().inArray())
                    gen.writeEndArray();
                gen.writeFieldName(subsection); //         "sectionName":
                gen.writeStartArray(); //            [
                lastSection = subsection;
            }
            boolean isOverridden = (Boolean) (en.getMethod("isOverridden")).invoke(v);
            gen.writeStartObject(); //               {
            gen.writeStringField(key, valueAsString); //                     "key": "value"   
            gen.writeStringField("description", valueDescription); //                  ,"description":"description"
            gen.writeStringField("type", type.getSimpleName()); //                  ,"type":"type"
            gen.writeBooleanField("editable", isEditable); //                  ,"editable":"true|false"
            gen.writeBooleanField("visible", isVisible); //                  ,"visible":"true|false"
            gen.writeBooleanField("overridden", isOverridden); //                  ,"overridden":"true|false"
            gen.writeEndObject(); //               }
        }
        if (gen.getOutputContext().inArray())
            gen.writeEndArray(); //            ]
        gen.writeEndObject(); //      }
        gen.writeEndObject(); //}
        gen.close();
        return sw.toString();
    } catch (Exception e) {
        BaasBoxLogger.error("Cannot generate a json for " + en.getSimpleName()
                + " Enum. Is it an Enum that implements the IProperties interface?", e);
    }
    return "{}";
}

From source file:com.cloudera.exhibit.server.json.ExhibitSerializer.java

@Override
public void serialize(Exhibit exhibit, JsonGenerator gen, SerializerProvider provider) throws IOException {
    ExhibitDescriptor desc = exhibit.descriptor();
    // start object
    gen.writeStartObject();/*from  w ww  .  ja v a2s .com*/

    // Write attrs
    gen.writeObjectFieldStart("attrs");
    serializeObs(exhibit.attributes(), exhibit.attributes().descriptor(), gen);
    gen.writeEndObject();

    // Write frame column names
    gen.writeObjectFieldStart("columns");
    for (Map.Entry<String, ObsDescriptor> fd : desc.frames().entrySet()) {
        gen.writeArrayFieldStart(fd.getKey());
        for (ObsDescriptor.Field f : fd.getValue()) {
            // TODO: type info?
            gen.writeString(f.name);
        }
        gen.writeEndArray();
    }
    gen.writeEndObject();

    // Write frame obs
    gen.writeObjectFieldStart("frames");
    for (Map.Entry<String, ObsDescriptor> fd : desc.frames().entrySet()) {
        gen.writeArrayFieldStart(fd.getKey());
        ObsDescriptor od = fd.getValue();
        for (Obs obs : exhibit.frames().get(fd.getKey())) {
            gen.writeStartArray();
            serializeObsArray(obs, fd.getValue(), gen);
            gen.writeEndArray();
        }
        gen.writeEndArray();
    }
    gen.writeEndObject();

    // finish object
    gen.writeEndObject();
}

From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java

private void writeGeoPolygon(JsonGenerator json, final Polygon polygon) throws IOException {
    json.writeStartArray();
    writeGeoPoints(json, polygon.getExterior());
    json.writeEndArray();/*w ww.j a v a 2s .c o m*/
    for (int i = 0; i < polygon.getNumberOfInteriorRings(); i++) {
        json.writeStartArray();
        writeGeoPoints(json, polygon.getInterior(i));
        json.writeEndArray();
    }
}

From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java

private void writePrimitiveCollection(final EdmPrimitiveType type, final Property property,
        final Boolean isNullable, final Integer maxLength, final Integer precision, final Integer scale,
        final Boolean isUnicode, final JsonGenerator json) throws IOException, SerializerException {
    json.writeStartArray();
    for (Object value : property.asCollection()) {
        switch (property.getValueType()) {
        case COLLECTION_PRIMITIVE:
        case COLLECTION_ENUM:
        case COLLECTION_GEOSPATIAL:
            try {
                writePrimitiveValue(property.getName(), type, value, isNullable, maxLength, precision, scale,
                        isUnicode, json);
            } catch (EdmPrimitiveTypeException e) {
                throw new SerializerException("Wrong value for property!", e,
                        SerializerException.MessageKeys.WRONG_PROPERTY_VALUE, property.getName(),
                        property.getValue().toString());
            }//w  w w.j  a va 2s. c o m
            break;
        default:
            throw new SerializerException("Property type not yet supported!",
                    SerializerException.MessageKeys.UNSUPPORTED_PROPERTY_TYPE, property.getName());
        }
    }
    json.writeEndArray();
}

From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java

protected void writeEntitySet(final ServiceMetadata metadata, final EdmEntityType entityType,
        final AbstractEntityCollection entitySet, final ExpandOption expand, Integer toDepth,
        final SelectOption select, final boolean onlyReference, final Set<String> ancestors, String name,
        final JsonGenerator json) throws IOException, SerializerException, DecoderException {
    json.writeStartArray();
    for (final Entity entity : entitySet) {
        if (onlyReference) {
            json.writeStartObject();/*ww w. ja va  2s  .  c  om*/
            json.writeStringField(constants.getId(), getEntityId(entity, entityType, name));
            json.writeEndObject();
        } else {
            writeEntity(metadata, entityType, entity, null, expand, toDepth, select, false, ancestors, name,
                    json);
        }
    }
    json.writeEndArray();
}

From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java

private void writeGeoPoints(JsonGenerator json, final ComposedGeospatial<Point> points) throws IOException {
    for (final Point point : points) {
        json.writeStartArray();
        writeGeoPoint(json, point);/*from  w w w  .  ja va2s  .c o m*/
        json.writeEndArray();
    }
}

From source file:com.castlemock.web.mock.rest.converter.swagger.SwaggerRestDefinitionConverter.java

/**
 * The method generates a response body based on a given name, {@link Property} and a map of {@link Model}.
 * @param name The name of the property.
 * @param property The property that will be part of the response.
 * @param definitions The map of definitions will be used when composing the response body.
 * @param generator The {@link JsonGenerator}.
 * @throws IOException/*  www  . j  av  a 2 s. c o m*/
 * @since 1.13
 * @see {@link #generateJsonBody(Response, Map)}
 */
private void generateJsonBody(final String name, final Property property, final Map<String, Model> definitions,
        final JsonGenerator generator) throws IOException {

    if (name != null) {
        generator.writeFieldName(name);
    }

    if (property instanceof RefProperty) {
        final RefProperty refProperty = (RefProperty) property;
        final String simpleRef = refProperty.getSimpleRef();
        final Model model = definitions.get(simpleRef);

        if (model == null) {
            LOGGER.warn("Unable to find the following definition in the Swagger file: " + simpleRef);
            return;
        }
        generateJsonBody(model, definitions, generator);
    } else if (property instanceof ArrayProperty) {
        final ArrayProperty arrayProperty = (ArrayProperty) property;
        final Property item = arrayProperty.getItems();
        final int maxItems = getMaxItems(arrayProperty.getMaxItems());
        generator.writeStartArray();

        for (int index = 0; index < maxItems; index++) {
            generateJsonBody(item.getName(), item, definitions, generator);
        }
        generator.writeEndArray();
    } else {
        String expression = getExpressionIdentifier(property);

        if (expression != null) {
            generator.writeObject(expression);
        } else {
            // Unsupported type. Need to write something otherwise
            // we might have a serialization problem.
            generator.writeObject("");
        }
    }
}

From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java

private void writeComplexCollection(final ServiceMetadata metadata, final EdmComplexType type,
        final Property property, final Set<List<String>> selectedPaths, final JsonGenerator json,
        Set<List<String>> expandedPaths, Linked linked, ExpandOption expand)
        throws IOException, SerializerException {
    json.writeStartArray();
    EdmComplexType derivedType = type;/*ww w.  jav a2 s  .c om*/
    Set<List<String>> expandedPaths1 = expandedPaths != null && !expandedPaths.isEmpty() ? expandedPaths
            : ExpandSelectHelper.getExpandedItemsPath(expand);
    for (Object value : property.asCollection()) {
        expandedPaths = expandedPaths1;
        derivedType = ((ComplexValue) value).getTypeName() != null
                ? metadata.getEdm().getComplexType(new FullQualifiedName(((ComplexValue) value).getTypeName()))
                : type;
        switch (property.getValueType()) {
        case COLLECTION_COMPLEX:
            json.writeStartObject();
            if (isODataMetadataFull || (!isODataMetadataNone && !derivedType.equals(type))) {
                json.writeStringField(constants.getType(),
                        "#" + derivedType.getFullQualifiedName().getFullQualifiedNameAsString());
            }
            expandedPaths = expandedPaths == null || expandedPaths.isEmpty() ? null
                    : ExpandSelectHelper.getReducedExpandItemsPaths(expandedPaths, property.getName());
            writeComplexValue(metadata, derivedType, ((ComplexValue) value).getValue(), selectedPaths, json,
                    expandedPaths, (ComplexValue) value, expand, property.getName());
            json.writeEndObject();
            break;
        default:
            throw new SerializerException("Property type not yet supported!",
                    SerializerException.MessageKeys.UNSUPPORTED_PROPERTY_TYPE, property.getName());
        }
    }
    json.writeEndArray();
}