List of usage examples for com.fasterxml.jackson.core JsonFactory createGenerator
public JsonGenerator createGenerator(Writer out) throws IOException
From source file:ch.rasc.wampspring.message.PublishMessage.java
@Override public String toJson(JsonFactory jsonFactory) throws IOException { try (StringWriter sw = new StringWriter(); JsonGenerator jg = jsonFactory.createGenerator(sw)) { jg.writeStartArray();//from w w w. j a v a 2s . c om jg.writeNumber(getTypeId()); jg.writeString(getTopicURI()); jg.writeObject(this.event); if (this.excludeMe != null && this.excludeMe) { jg.writeBoolean(true); } else if (this.exclude != null) { jg.writeObject(this.exclude); if (this.eligible != null) { jg.writeObject(this.eligible); } } jg.writeEndArray(); jg.close(); return sw.toString(); } }
From source file:com.messagehub.samples.servlet.MessageList.java
/** * Build message list dependent on the format Message Hub requires. The * message list is in the form: [{ "value": base_64_string }, ...] * * @return {String} String representation of a JSON object. * @throws IOException/*from w w w . j av a 2 s . co m*/ */ public String build() throws IOException { final JsonFactory jsonFactory = new JsonFactory(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonGenerator jsonGenerator = null; jsonGenerator = jsonFactory.createGenerator(outputStream); jsonGenerator.writeStartArray(); // Write each message as a JSON object in // the form: // { "value": base_64_string } for (int i = 0; i < this.messages.size(); i++) { jsonGenerator.writeStartObject(); jsonGenerator.writeFieldName("value"); jsonGenerator.writeObject(this.messages.get(i)); jsonGenerator.writeEndObject(); } jsonGenerator.writeEndArray(); // Close underlying streams and return string representation. jsonGenerator.close(); outputStream.close(); return new String(outputStream.toByteArray()); }
From source file:com.example.MessageList.java
/** * Build message list dependent on the format Message Hub requires. The * message list is in the form: [{ "value": base_64_string }, ...] * /*from w ww .j a v a2 s .c o m*/ * @return {String} String representation of a JSON object. * @throws IOException */ public String build() throws IOException { final JsonFactory jsonFactory = new JsonFactory(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonGenerator jsonGenerator = null; jsonGenerator = jsonFactory.createGenerator(outputStream); // [ jsonGenerator.writeStartArray(); // Write each message as a JSON object in // the form: // { "value": base_64_string } for (int i = 0; i < this.messages.size(); i++) { jsonGenerator.writeStartObject(); jsonGenerator.writeFieldName("value"); jsonGenerator.writeObject(this.messages.get(i)); jsonGenerator.writeEndObject(); } // ] jsonGenerator.writeEndArray(); // Close underlying streams and return string representation. jsonGenerator.close(); outputStream.close(); return new String(outputStream.toByteArray()); }
From source file:com.github.jonpeterson.jackson.module.versioning.VersionedModelSerializer.java
private void doSerialize(T value, JsonGenerator generator, SerializerProvider provider, TypeSerializer typeSerializer) throws IOException { // serialize the value into a byte array buffer then parse it back out into a JsonNode tree // TODO: find a better way to convert the value into a tree JsonFactory factory = generator.getCodec().getFactory(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(4096); JsonGenerator bufferGenerator = factory.createGenerator(buffer); try {//from w w w . j a va 2s . c o m if (typeSerializer != null) delegate.serializeWithType(value, bufferGenerator, provider, typeSerializer); else delegate.serialize(value, bufferGenerator, provider); } finally { bufferGenerator.close(); } ObjectNode modelData = factory.createParser(buffer.toByteArray()).readValueAsTree(); // set target version to @SerializeToVersion's value, @JsonVersionModel's defaultSerializeToVersion, or // @JsonVersionModel's currentVersion in that order String targetVersion = null; if (serializeToVersionProperty != null) { targetVersion = (String) serializeToVersionProperty.getAccessor().getValue(value); modelData.remove(serializeToVersionProperty.getName()); } if (targetVersion == null) targetVersion = jsonVersionedModel.defaultSerializeToVersion(); if (targetVersion.isEmpty()) targetVersion = jsonVersionedModel.currentVersion(); // convert model data if there is a converter and targetVersion is different than the currentVersion or if // alwaysConvert is true if (converter != null && (jsonVersionedModel.alwaysConvert() || !targetVersion.equals(jsonVersionedModel.currentVersion()))) modelData = converter.convert(modelData, jsonVersionedModel.currentVersion(), targetVersion, JsonNodeFactory.instance); // add target version to model data if it wasn't the version to suppress if (!targetVersion.equals(jsonVersionedModel.versionToSuppressPropertySerialization())) modelData.put(jsonVersionedModel.propertyName(), targetVersion); // write node generator.writeTree(modelData); }
From source file:org.cloudcoder.dataanalysis.ProgsnapExport.java
private String encodeLine(String tagname, Object value) throws IOException { StringWriter sw = new StringWriter(); JsonFactory factory = new JsonFactory(); JsonGenerator jg = factory.createGenerator(sw); jg.writeStartObject();//from w w w .j a v a 2s. c o m jg.writeStringField("tag", tagname); jg.writeFieldName("value"); writeJsonFieldValue(jg, value); jg.writeEndObject(); jg.close(); return sw.toString(); }
From source file:org.zalando.logbook.JsonHttpLogFormatter.java
private String compactJson(final String json) throws IOException { if (isAlreadyCompacted(json)) { return json; }/*from ww w.j ava2 s . c o m*/ final StringWriter output = new StringWriter(); final JsonFactory factory = mapper.getFactory(); final JsonParser parser = factory.createParser(json); final JsonGenerator generator = factory.createGenerator(output); // https://github.com/jacoco/jacoco/wiki/FilteringOptions //noinspection TryFinallyCanBeTryWithResources - jacoco can't handle try-with correctly try { while (parser.nextToken() != null) { generator.copyCurrentEvent(parser); } } finally { generator.close(); } return output.toString(); }
From source file:com.joliciel.jochre.search.highlight.Snippet.java
public String toJson() { try {/* ww w . j a v a2 s . c o m*/ DecimalFormatSymbols enSymbols = new DecimalFormatSymbols(Locale.US); DecimalFormat df = new DecimalFormat("0.00", enSymbols); StringWriter writer = new StringWriter(); JsonFactory jsonFactory = new JsonFactory(); JsonGenerator jsonGen = jsonFactory.createGenerator(writer); this.toJson(jsonGen, df); writer.flush(); String json = writer.toString(); return json; } catch (IOException ioe) { LogUtils.logError(LOG, ioe); throw new RuntimeException(ioe); } }
From source file:com.crossover.trial.weather.domain.AirportTest.java
@Test public void testSerialization() throws IOException { JsonFactory jsonFactory = new MappingJsonFactory(); Airport airport = new Airport.Builder().withIata("aaa").withLatitude(10).withLongitude(20).build(); StringWriter out = new StringWriter(); JsonGenerator json = jsonFactory.createGenerator(out); json.writeObject(airport);//www . j a v a 2s .co m json.close(); assertThat(out.toString(), equalTo("{\"iata\":\"AAA\",\"latitude\":10.0,\"longitude\":20.0}")); }
From source file:org.graylog.plugins.nats.output.AbstractGelfNatsOutput.java
protected byte[] toGELFMessage(final Message message) throws IOException { final HashMap<String, Object> fields = new HashMap<>(message.getFields()); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(512); final JsonFactory jsonFactory = new JsonFactory(); final JsonGenerator generator = jsonFactory.createGenerator(outputStream); generator.writeStartObject();/* w ww . jav a 2 s . com*/ generator.writeStringField("version", "1.1"); generator.writeStringField("host", (String) fields.remove(Message.FIELD_SOURCE)); generator.writeStringField("short_message", (String) fields.remove(Message.FIELD_MESSAGE)); final String fullMessage = (String) fields.remove(Message.FIELD_FULL_MESSAGE); if (fullMessage != null) { generator.writeStringField("full_message", fullMessage); } final Object fieldTimeStamp = fields.remove(Message.FIELD_TIMESTAMP); final DateTime timestamp; if (fieldTimeStamp instanceof DateTime) { timestamp = (DateTime) fieldTimeStamp; } else { timestamp = Tools.nowUTC(); } generator.writeNumberField("timestamp", timestamp.getMillis() / 1000d); final Object fieldLevel = fields.remove(Message.FIELD_TIMESTAMP); final Integer level = extractLevel(fieldLevel); if (level != null) { generator.writeNumberField("level", level); } for (Map.Entry<String, Object> field : fields.entrySet()) { final String key = field.getKey(); final Object value = field.getValue(); if (value instanceof String) { generator.writeStringField(key, (String) value); } else if (value instanceof Boolean) { generator.writeBooleanField(key, (Boolean) value); } else if (value instanceof Integer) { generator.writeNumberField(key, (Integer) value); } else if (value instanceof Long) { generator.writeNumberField(key, (Long) value); } else if (value instanceof Float) { generator.writeNumberField(key, (Float) value); } else if (value instanceof Double) { generator.writeNumberField(key, (Double) value); } else if (value instanceof BigDecimal) { generator.writeNumberField(key, (BigDecimal) value); } else if (value == null) { generator.writeNullField(key); } } generator.writeStringField("_forwarder_cluster_id", clusterId); generator.writeStringField("_forwarder_node_id", nodeId); generator.writeEndObject(); generator.flush(); return outputStream.toByteArray(); }
From source file:org.eclipse.winery.repository.resources.servicetemplates.boundarydefinitions.interfaces.ExportedOperationResource.java
@GET @Produces(MediaType.APPLICATION_JSON)/*from ww w. j av a2s. co m*/ public Response getJSON() { JsonFactory jsonFactory = new JsonFactory(); StringWriter sw = new StringWriter(); try { JsonGenerator jg = jsonFactory.createGenerator(sw); jg.writeStartObject(); String type = this.getType(); jg.writeStringField("type", type); jg.writeStringField("ref", this.getReference()); if ((type != null) && (!type.equals("Plan"))) { jg.writeStringField("interfacename", this.getInterfaceName()); jg.writeStringField("operationname", this.getOperationName()); } jg.writeEndObject(); jg.close(); } catch (Exception e) { ExportedOperationResource.LOGGER.error(e.getMessage(), e); throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity(e).build()); } return Response.ok(sw.toString()).build(); }