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:org.h2gis.drivers.geojson.GeoJsonWriteDriver.java

/**
 * Coordinates of a MultiLineString are an array of LineString coordinate
 * arrays:/*w  ww .  j a v a2s .  com*/
 *
 * { "type": "MultiLineString", "coordinates": [ [ [100.0, 0.0], [101.0,
 * 1.0] ], [ [102.0, 2.0], [103.0, 3.0] ] ] }
 *
 * @param geom
 * @param gen
 * @throws IOException
 */
private void write(MultiLineString geom, JsonGenerator gen) throws IOException {
    gen.writeStringField("type", "MultiLineString");
    gen.writeFieldName("coordinates");
    gen.writeStartArray();
    for (int i = 0; i < geom.getNumGeometries(); ++i) {
        writeCoordinates(geom.getGeometryN(i).getCoordinates(), gen);
    }
    gen.writeEndArray();
}

From source file:org.h2gis.drivers.geojson.GeoJsonWriteDriver.java

/**
 *
 *
 * Coordinates of a MultiPolygon are an array of Polygon coordinate arrays:
 *
 * { "type": "MultiPolygon", "coordinates": [ [[[102.0, 2.0], [103.0, 2.0],
 * [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], [[[100.0, 0.0], [101.0, 0.0],
 * [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], [[100.2, 0.2], [100.8, 0.2],
 * [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] ] }
 *
 * @param geom/*from  ww w  .java  2s .c  o m*/
 * @param gen
 * @throws IOException
 */
private void write(MultiPolygon geom, JsonGenerator gen) throws IOException {
    gen.writeStringField("type", "MultiPolygon");
    gen.writeFieldName("coordinates");
    gen.writeStartArray();
    for (int i = 0; i < geom.getNumGeometries(); ++i) {
        Polygon p = (Polygon) geom.getGeometryN(i);
        gen.writeStartArray();
        writeCoordinates(p.getExteriorRing().getCoordinates(), gen);
        for (int j = 0; j < p.getNumInteriorRing(); ++j) {
            writeCoordinates(p.getInteriorRingN(j).getCoordinates(), gen);
        }
        gen.writeEndArray();
    }
    gen.writeEndArray();
}

From source file:org.eclipse.winery.repository.rest.resources.AbstractComponentsResource.java

/**
 * Used by org.eclipse.winery.repository.repository.client and by the artifactcreationdialog.tag. Especially the
 * "name" field is used there at the UI/*from  w w  w. j a v a2s . co m*/
 *
 * @param grouped if given, the JSON output is grouped by namespace
 * @return A list of all ids of all instances of this component type. <br /> Format: <code>[({"namespace":
 * "[namespace]", "id": "[id]"},)* ]</code>. <br /><br /> If grouped is set, the list will be grouped by namespace.
 * <br /> <code>[{"id": "[namsepace encoded]", "test": "[namespace decoded]", "children":[{"id": "[qName]", "text":
 * "[id]"}]}]</code>
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getListOfAllIds(@QueryParam("grouped") String grouped) {
    Class<? extends TOSCAComponentId> idClass = RestUtils
            .getComponentIdClassForComponentContainer(this.getClass());
    boolean supportsNameAttribute = Util.instanceSupportsNameAttribute(idClass);
    SortedSet<? extends TOSCAComponentId> allTOSCAcomponentIds = RepositoryFactory.getRepository()
            .getAllTOSCAComponentIds(idClass);
    JsonFactory jsonFactory = new JsonFactory();
    StringWriter sw = new StringWriter();
    try {
        JsonGenerator jg = jsonFactory.createGenerator(sw);
        // We produce org.eclipse.winery.repository.client.WineryRepositoryClient.NamespaceAndId by hand here
        // Refactoring could move this class to common and fill it here
        if (grouped == null) {
            jg.writeStartArray();
            for (TOSCAComponentId id : allTOSCAcomponentIds) {
                jg.writeStartObject();
                jg.writeStringField("namespace", id.getNamespace().getDecoded());
                jg.writeStringField("id", id.getXmlId().getDecoded());
                if (supportsNameAttribute) {
                    AbstractComponentInstanceResource componentInstaceResource = AbstractComponentsResource
                            .getComponentInstaceResource(id);
                    String name = ((IHasName) componentInstaceResource).getName();
                    jg.writeStringField("name", name);
                } else {
                    // used for winery-qNameSelector to avoid an if there
                    jg.writeStringField("name", id.getXmlId().getDecoded());
                }
                jg.writeStringField("qName", id.getQName().toString());
                jg.writeEndObject();
            }
            jg.writeEndArray();
        } else {
            jg.writeStartArray();
            Map<Namespace, ? extends List<? extends TOSCAComponentId>> groupedIds = allTOSCAcomponentIds
                    .stream().collect(Collectors.groupingBy(id -> id.getNamespace()));
            groupedIds.keySet().stream().sorted().forEach(namespace -> {
                try {
                    jg.writeStartObject();
                    jg.writeStringField("id", namespace.getEncoded());
                    jg.writeStringField("text", namespace.getDecoded());
                    jg.writeFieldName("children");
                    jg.writeStartArray();
                    groupedIds.get(namespace).forEach(id -> {
                        try {
                            jg.writeStartObject();
                            String text;
                            if (supportsNameAttribute) {
                                AbstractComponentInstanceResource componentInstaceResource = AbstractComponentsResource
                                        .getComponentInstaceResource(id);
                                text = ((IHasName) componentInstaceResource).getName();
                            } else {
                                text = id.getXmlId().getDecoded();
                            }
                            jg.writeStringField("id", id.getQName().toString());
                            jg.writeStringField("text", text);
                            jg.writeEndObject();
                        } catch (IOException e) {
                            AbstractComponentsResource.LOGGER.error("Could not create JSON", e);
                        }
                    });
                    jg.writeEndArray();
                    jg.writeEndObject();
                } catch (IOException e) {
                    AbstractComponentsResource.LOGGER.error("Could not create JSON", e);
                }
            });
            jg.writeEndArray();
        }
        jg.close();
    } catch (Exception e) {
        AbstractComponentsResource.LOGGER.error(e.getMessage(), e);
        return "[]";
    }
    return sw.toString();
}

From source file:org.apache.nifi.processors.elasticsearch.PutElasticsearchHttpRecord.java

private void writeArray(final Object[] values, final String fieldName, final JsonGenerator generator,
        final DataType elementType) throws IOException {
    generator.writeStartArray();
    for (final Object element : values) {
        writeValue(generator, element, fieldName, elementType);
    }/*  w w w  .ja  v a 2 s.  c o  m*/
    generator.writeEndArray();
}

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

public void generate(final JsonGenerator generator, Resource resource) {
    prepare(generator, resource);//w w  w. j a  va 2  s .c  om

    final EList<EObject> contents = resource.getContents();

    if (contents.size() == 1) {
        try {
            generate(generator, contents.get(0));
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        try {
            generator.writeStartArray();
            for (final EObject current : contents) {
                generate(generator, current);
            }
            generator.writeEndArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.basho.riak.client.query.MapReduce.java

/**
 * Creates the JSON string of the M/R job for submitting to the
 * {@link RawClient}/*  w  w w. j a v a  2s . c o m*/
 * 
 * Uses Jackson to write out the JSON string. I'm not very happy with this
 * method, it is a candidate for change.
 * 
 * TODO re-evaluate this method, look for something smaller and more elegant.
 * 
 * @return a String of JSON
 * @throws RiakException
 *             if, for some reason, we can't create a JSON string.
 */
private String writeSpec() throws RiakException {

    final ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        JsonGenerator jg = new JsonFactory().createJsonGenerator(out, JsonEncoding.UTF8);
        jg.setCodec(new ObjectMapper());

        jg.writeStartObject();

        jg.writeFieldName("inputs");
        writeInput(jg);

        jg.writeFieldName("query");
        jg.writeStartArray();

        writePhases(jg);

        jg.writeEndArray();
        if (timeout != null) {
            jg.writeNumberField("timeout", timeout);
        }

        jg.writeEndObject();
        jg.flush();

        return out.toString("UTF8");
    } catch (IOException e) {
        throw new RiakException(e);
    }
}

From source file:org.neo4j.ontology.server.unmanaged.AnnotationResource.java

@GET
@Produces(MediaType.APPLICATION_JSON)//from  w w  w. j  a v a2 s.  co m
@Path("/{userName}")
public Response getAnnotationSets(final @PathParam("userName") String userName,
        final @DefaultValue("0") @QueryParam("objectification") int objectification) {
    StreamingOutput stream = new StreamingOutput() {
        @Override
        public void write(OutputStream os) throws IOException, WebApplicationException {
            Map<Long, List<Long>> associatedDataSets = new HashMap<>();
            Label annotationLabel = DynamicLabel.label("AnnotationSets" + capitalize(userName));

            JsonGenerator jg = objectMapper.getFactory().createGenerator(os, JsonEncoding.UTF8);
            jg.writeStartObject();
            jg.writeFieldName("nodes");

            if (objectification > 0) {
                jg.writeStartObject();
            } else {
                jg.writeStartArray();
            }

            try (Transaction tx = graphDb.beginTx();
                    ResourceIterator<Node> users = graphDb.findNodes(USER, "name", userName)) {
                if (users.hasNext()) {
                    getDirectAnnotationTerms(getAccessibleDataSets(users.next()), associatedDataSets);
                }
                tx.success();
            }

            try (Transaction tx = graphDb.beginTx();
                    ResourceIterator<Node> terms = graphDb.findNodes(annotationLabel)) {
                while (terms.hasNext()) {
                    Node term = terms.next();
                    if (objectification > 0) {
                        jg.writeFieldName(term.getProperty("uri").toString());
                    }
                    if (objectification > 1) {
                        if (associatedDataSets.containsKey(term.getId())) {
                            writeJsonNodeObjectifiedObject(jg, term, annotationLabel,
                                    associatedDataSets.get(term.getId()));
                        } else {
                            writeJsonNodeObjectifiedObject(jg, term, annotationLabel);
                        }
                    } else {
                        if (associatedDataSets.containsKey(term.getId())) {
                            writeJsonNodeObject(jg, term, annotationLabel,
                                    associatedDataSets.get(term.getId()));
                        } else {
                            writeJsonNodeObject(jg, term, annotationLabel);
                        }
                    }
                }
                tx.success();
            }

            if (objectification > 0) {
                jg.writeEndObject();
            } else {
                jg.writeEndArray();
            }
            jg.writeEndObject();
            jg.flush();
            jg.close();
        }
    };

    return Response.ok().entity(stream).type(MediaType.APPLICATION_JSON).build();
}

From source file:org.solmix.datax.wmix.serializer.DataServiceInfoSerializer.java

/**
 * {@inheritDoc}/*ww w . j  a va2s  .  c  om*/
 * 
 * @see com.fasterxml.jackson.databind.JsonSerializer#serialize(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider)
 */
@Override
public void serialize(DataServiceInfo value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    jgen.writeStringField("ID", value.getId());
    //        jgen.writeStringField("recordXPath", "/data");
    jgen.writeStringField("dataFormat", "json");
    jgen.writeBooleanField("clientOnly", false);
    List<FieldInfo> fields = value.getFields();
    if (DataUtils.isNotNullAndEmpty(fields)) {
        jgen.writeFieldName("fields");
        jgen.writeStartArray();

        for (FieldInfo f : fields) {
            jgen.writeObject(convertFiledToMap(f));

        }
        jgen.writeEndArray();
    }
    Collection<OperationInfo> operations = value.getOperations();
    if (operations != null) {
        Iterator<OperationInfo> it = operations.iterator();
        jgen.writeFieldName("operationBindings");
        jgen.writeStartArray();
        while (it.hasNext()) {
            OperationInfo oi = it.next();
            jgen.writeStartObject();
            jgen.writeStringField("operationType", oi.getType().value());
            jgen.writeStringField("operationId", oi.getId());
            jgen.writeEndObject();
        }
        jgen.writeEndArray();
    }
    jgen.writeEndObject();
}

From source file:models.ReferenceSerializer.java

@Override
public void serialize(Reference reference, JsonGenerator jgen, SerializerProvider provider) throws IOException {
    jgen.writeStartObject();//from ww  w. j av a  2  s  .  co  m
    jgen.writeStringField("id", reference.getId());
    jgen.writeStringField("date", reference.getDate());
    jgen.writeStringField("publisher", reference.getPublisher());
    jgen.writeStringField("shortName", reference.getShortName());
    jgen.writeStringField("source", reference.getSource());
    jgen.writeStringField("title", reference.getTitle());
    jgen.writeStringField("url", reference.getURL());
    jgen.writeStringField("creator", reference.getCreator());
    jgen.writeFieldName("groups");
    jgen.writeStartArray();
    for (Group group : reference.getGroups()) {
        writeSimplifiedGroup(group, jgen);
    }
    jgen.writeEndArray();
    jgen.writeEndObject();
}

From source file:TDS.Shared.Messages.MessageJson.java

private void writeMessageElement(Message message, JsonGenerator jsonWriter)
        throws JsonGenerationException, IOException {
    // {"id":10884,
    // "m":"Global.Path.Help",
    // "t_a":[{"t":"..\/Projects\/Oregon\/Help\/help.html",
    // "l":"ENU"}]
    // }//  ww w  .  j a  v  a 2  s. co  m
    jsonWriter.writeStartObject(); // {
    jsonWriter.writeNumberField("id", message.getMessageId());
    jsonWriter.writeStringField("m", message.getMessageKey());

    jsonWriter.writeFieldName("t_a"); // "t_a":
    jsonWriter.writeStartArray(); // [

    List<MessageTranslation> translations;

    // if there is no language specified they get all translations
    if (StringUtils.isEmpty(_language)) {
        translations = message.getTranslations();
    } else {
        // if a language is provided then find the best language and only
        // include that
        MessageTranslation defaultTranslation = message.getTranslation(_language, _subject, _grade);
        translations = new ArrayList<MessageTranslation>();
        translations.add(defaultTranslation);
    }

    for (MessageTranslation translation : translations) {
        writeTranslationElement(translation, jsonWriter);
    }

    jsonWriter.writeEndArray(); // ]
    jsonWriter.writeEndObject(); // }
}