List of usage examples for com.fasterxml.jackson.core JsonGenerator writeObject
public abstract void writeObject(Object pojo) throws IOException, JsonProcessingException;
From source file:com.strategicgains.hyperexpress.serialization.jackson.HalResourceSerializer.java
private void writeLinks(HalResource resource, boolean isEmbedded, JsonGenerator jgen) throws JsonGenerationException, IOException { List<Link> links = resource.getLinks(); List<Namespace> namespaces = resource.getNamespaces(); if (links.isEmpty() && (isEmbedded || namespaces.isEmpty())) return;//from ww w .jav a 2s. com jgen.writeObjectFieldStart(LINKS); writeCuries(namespaces, isEmbedded, jgen); Map<String, List<HalLink>> linksByRel = indexLinksByRel(resource.getLinks()); for (Entry<String, List<HalLink>> entry : linksByRel.entrySet()) { if (entry.getValue().size() == 1 && !resource.isMultipleLinks(entry.getKey())) // Write single link { HalLink link = entry.getValue().iterator().next(); if (null == link.getTemplated()) { link.setTemplated(link.hasTemplate() ? true : null); } jgen.writeObjectField(entry.getKey(), link); } else // Write link array { jgen.writeArrayFieldStart(entry.getKey()); for (HalLink link : entry.getValue()) { if (null == link.getTemplated()) { link.setTemplated(link.hasTemplate() ? true : null); } jgen.writeObject(link); } jgen.writeEndArray(); } } jgen.writeEndObject(); }
From source file:org.numenta.nupic.algorithms.CLAClassifierSerializer.java
@Override public void serialize(CLAClassifier cla, JsonGenerator jgen, SerializerProvider arg2) throws IOException, JsonProcessingException { jgen.writeStartObject();//from w ww . j av a 2 s.co m jgen.writeNumberField("alpha", cla.alpha); jgen.writeNumberField("actValueAlpha", cla.actValueAlpha); jgen.writeNumberField("learnIteration", cla.learnIteration); jgen.writeNumberField("recordNumMinusLearnIteration", cla.recordNumMinusLearnIteration); jgen.writeNumberField("maxBucketIdx", cla.maxBucketIdx); StringBuilder sb = new StringBuilder(); for (int i : cla.steps.toArray()) { sb.append(i).append(","); } sb.setLength(sb.length() - 1); jgen.writeStringField("steps", sb.toString()); sb = new StringBuilder(); for (Tuple t : cla.patternNZHistory) { sb.append(t.get(0)).append("-").append(Arrays.toString((int[]) t.get(1))).append(";"); } sb.setLength(sb.length() - 1); jgen.writeStringField("patternNZHistory", sb.toString()); sb = new StringBuilder(); for (Tuple t : cla.activeBitHistory.keySet()) { sb.append(t.get(0)).append(",").append(t.get(1)).append("-"); BitHistory bh = cla.activeBitHistory.get(t); sb.append(bh.id).append("=").append(bh.stats).append("=").append(bh.lastTotalUpdate).append(";"); } sb.setLength(sb.length() - 1); jgen.writeStringField("activeBitHistory", sb.toString()); jgen.writeArrayFieldStart("actualValues"); for (Object o : cla.actualValues) { jgen.writeObject(o); } jgen.writeEndArray(); jgen.writeEndObject(); }
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/*from w w w . ja v a 2 s . com*/ * @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.commons.core.data.JSONEntrySerializer.java
@Override protected void doSerialize(final JSONEntryImpl entry, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject();/*from w w w . j ava 2 s . c o m*/ if (entry.getMetadata() != null) { jgen.writeStringField(Constants.JSON_METADATA, entry.getMetadata().toASCIIString()); } if (entry.getId() != null) { jgen.writeStringField(Constants.JSON_ID, entry.getId()); } final Map<String, List<String>> entitySetLinks = new HashMap<String, List<String>>(); for (Link link : entry.getNavigationLinks()) { ODataLinkType type = null; try { type = ODataLinkType.fromString(version, link.getRel(), link.getType()); } catch (IllegalArgumentException e) { // ignore } if (type == ODataLinkType.ENTITY_SET_NAVIGATION) { final List<String> uris; if (entitySetLinks.containsKey(link.getTitle())) { uris = entitySetLinks.get(link.getTitle()); } else { uris = new ArrayList<String>(); entitySetLinks.put(link.getTitle(), uris); } uris.add(link.getHref()); } else { if (StringUtils.isNotBlank(link.getHref())) { jgen.writeStringField(link.getTitle() + Constants.JSON_BIND_LINK_SUFFIX, link.getHref()); } } if (link.getInlineEntry() != null) { jgen.writeObjectField(link.getTitle(), link.getInlineEntry()); } else if (link.getInlineFeed() != null) { jgen.writeArrayFieldStart(link.getTitle()); for (Entry subEntry : link.getInlineFeed().getEntries()) { jgen.writeObject(subEntry); } jgen.writeEndArray(); } } for (Map.Entry<String, List<String>> entitySetLink : entitySetLinks.entrySet()) { jgen.writeArrayFieldStart(entitySetLink.getKey() + Constants.JSON_BIND_LINK_SUFFIX); for (String uri : entitySetLink.getValue()) { jgen.writeString(uri); } jgen.writeEndArray(); } for (Link link : entry.getMediaEditLinks()) { if (link.getTitle() == null) { jgen.writeStringField(Constants.JSON_MEDIAEDIT_LINK, link.getHref()); } if (link.getInlineEntry() != null) { jgen.writeObjectField(link.getTitle(), link.getInlineEntry()); } if (link.getInlineFeed() != null) { jgen.writeArrayFieldStart(link.getTitle()); for (Entry subEntry : link.getInlineFeed().getEntries()) { jgen.writeObject(subEntry); } jgen.writeEndArray(); } } for (Property property : entry.getProperties()) { property(jgen, property, property.getName()); } jgen.writeEndObject(); }
From source file:ch.ralscha.extdirectspring.util.MapActionSerializer.java
@Override public void serialize(Map<String, List<Action>> value, JsonGenerator jgen, SerializerProvider provider) throws IOException { if (null != value) { jgen.writeStartObject();/*from w w w . j a v a2 s. co m*/ for (Entry<String, List<Action>> entry : value.entrySet()) { String key = entry.getKey(); jgen.writeArrayFieldStart(key); List<Action> actions = entry.getValue(); for (Action action : actions) { // PrettyPrinter is not set the generator is on one line // mode if (jgen.getPrettyPrinter() != null && action instanceof ActionDoc) {// insertion // of // doc // here ActionDoc actionDoc = (ActionDoc) action; jgen.writeRaw("\n\t/**"); if (actionDoc.isDeprecated()) { jgen.writeRaw("\n\t* @deprecated"); } jgen.writeRaw("\n\t* " + actionDoc.getName() + ": " + actionDoc.getMethodComment()); jgen.writeRaw("\n\t* @author: " + actionDoc.getAuthor()); jgen.writeRaw("\n\t* @version: " + actionDoc.getVersion()); jgen.writeRaw("\n\t*"); for (Entry<String, String> entry2 : actionDoc.getParameters().entrySet()) { jgen.writeRaw("\n\t* @param: [" + entry2.getKey() + "] " + entry2.getValue()); } jgen.writeRaw("\n\t* @return"); for (Entry<String, String> entry2 : actionDoc.getReturnMethod().entrySet()) { jgen.writeRaw("\n\t*\t [" + entry2.getKey() + "] " + entry2.getValue()); } jgen.writeRaw("\n\t*/\n"); } jgen.writeObject(action); } jgen.writeEndArray(); } jgen.writeEndObject(); } }
From source file:org.apache.airavata.db.AbstractThriftSerializer.java
@Override public void serialize(final T value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException { jgen.writeStartObject();/*from w w w . j a v a 2 s. c om*/ for (final E field : getFieldValues()) { if (value.isSet(field)) { final Object fieldValue = value.getFieldValue(field); if (fieldValue != null) { log.debug("Adding field {} to the JSON string...", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, field.getFieldName())); jgen.writeFieldName(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, field.getFieldName())); if (fieldValue instanceof Short) { jgen.writeNumber((Short) fieldValue); } else if (fieldValue instanceof Integer) { jgen.writeNumber((Integer) fieldValue); } else if (fieldValue instanceof Long) { jgen.writeNumber((Long) fieldValue); } else if (fieldValue instanceof Double) { jgen.writeNumber((Double) fieldValue); } else if (fieldValue instanceof Float) { jgen.writeNumber((Float) fieldValue); } else if (fieldValue instanceof Boolean) { jgen.writeBoolean((Boolean) fieldValue); } else if (fieldValue instanceof String) { jgen.writeString(fieldValue.toString()); } else if (fieldValue instanceof Collection) { log.debug("Array opened for field {}.", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, field.getFieldName())); jgen.writeStartArray(); for (final Object arrayObject : (Collection<?>) fieldValue) { jgen.writeObject(arrayObject); } jgen.writeEndArray(); log.debug("Array closed for field {}.", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, field.getFieldName())); } else { jgen.writeObject(fieldValue); } } else { log.debug("Skipping converting field {} to JSON: value is null!", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, field.getFieldName())); } } else { log.debug("Skipping converting field {} to JSON: field has not been set!", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, field.getFieldName())); } } jgen.writeEndObject(); }
From source file:org.apache.olingo.client.core.serialization.JsonEntitySerializer.java
protected void doContainerSerialize(final ResWrap<Entity> container, final JsonGenerator jgen) throws IOException, EdmPrimitiveTypeException { final Entity entity = container.getPayload(); jgen.writeStartObject();//w w w. ja va2 s. c om if (serverMode) { if (container.getContextURL() != null) { jgen.writeStringField(Constants.JSON_CONTEXT, container.getContextURL().toASCIIString()); } if (StringUtils.isNotBlank(container.getMetadataETag())) { jgen.writeStringField(Constants.JSON_METADATA_ETAG, container.getMetadataETag()); } if (StringUtils.isNotBlank(entity.getETag())) { jgen.writeStringField(Constants.JSON_ETAG, entity.getETag()); } } if (StringUtils.isNotBlank(entity.getType()) && !isODataMetadataNone(contentType)) { jgen.writeStringField(Constants.JSON_TYPE, new EdmTypeInfo.Builder().setTypeExpression(entity.getType()).build().external()); } if (entity.getId() != null && !isODataMetadataNone(contentType)) { jgen.writeStringField(Constants.JSON_ID, entity.getId().toASCIIString()); } for (Annotation annotation : entity.getAnnotations()) { valuable(jgen, annotation, "@" + annotation.getTerm()); } for (Property property : entity.getProperties()) { valuable(jgen, property, property.getName()); } if (serverMode && entity.getEditLink() != null && StringUtils.isNotBlank(entity.getEditLink().getHref())) { jgen.writeStringField(Constants.JSON_EDIT_LINK, entity.getEditLink().getHref()); if (entity.isMediaEntity()) { jgen.writeStringField(Constants.JSON_MEDIA_READ_LINK, entity.getEditLink().getHref() + "/$value"); } } if (!isODataMetadataNone(contentType)) { links(entity, jgen); } for (Link link : entity.getMediaEditLinks()) { if (link.getTitle() == null) { jgen.writeStringField(Constants.JSON_MEDIA_EDIT_LINK, link.getHref()); } if (link.getInlineEntity() != null) { jgen.writeObjectField(link.getTitle(), link.getInlineEntity()); } if (link.getInlineEntitySet() != null) { jgen.writeArrayFieldStart(link.getTitle()); for (Entity subEntry : link.getInlineEntitySet().getEntities()) { jgen.writeObject(subEntry); } jgen.writeEndArray(); } } if (serverMode) { for (Operation operation : entity.getOperations()) { jgen.writeObjectFieldStart( "#" + StringUtils.substringAfterLast(operation.getMetadataAnchor(), "#")); jgen.writeStringField(Constants.ATTR_TITLE, operation.getTitle()); jgen.writeStringField(Constants.ATTR_TARGET, operation.getTarget().toASCIIString()); jgen.writeEndObject(); } } jgen.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 .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); 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: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 www. j a v 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); } }
From source file:org.apache.olingo.commons.core.serialization.JsonEntitySerializer.java
protected void doContainerSerialize(final ResWrap<Entity> container, final JsonGenerator jgen) throws IOException, EdmPrimitiveTypeException { final Entity entity = container.getPayload(); jgen.writeStartObject();//from w w w. ja v a2 s .com if (serverMode) { if (container.getContextURL() != null) { jgen.writeStringField(version.compareTo(ODataServiceVersion.V40) >= 0 ? Constants.JSON_CONTEXT : Constants.JSON_METADATA, container.getContextURL().toASCIIString()); } if (version.compareTo(ODataServiceVersion.V40) >= 0 && StringUtils.isNotBlank(container.getMetadataETag())) { jgen.writeStringField(Constants.JSON_METADATA_ETAG, container.getMetadataETag()); } if (StringUtils.isNotBlank(entity.getETag())) { jgen.writeStringField(version.getJsonName(ODataServiceVersion.JsonKey.ETAG), entity.getETag()); } } if (StringUtils.isNotBlank(entity.getType())) { jgen.writeStringField(version.getJsonName(ODataServiceVersion.JsonKey.TYPE), new EdmTypeInfo.Builder().setTypeExpression(entity.getType()).build().external(version)); } if (entity.getId() != null) { jgen.writeStringField(version.getJsonName(ODataServiceVersion.JsonKey.ID), entity.getId().toASCIIString()); } for (Annotation annotation : entity.getAnnotations()) { valuable(jgen, annotation, "@" + annotation.getTerm()); } for (Property property : entity.getProperties()) { valuable(jgen, property, property.getName()); } if (serverMode && entity.getEditLink() != null && StringUtils.isNotBlank(entity.getEditLink().getHref())) { jgen.writeStringField(version.getJsonName(ODataServiceVersion.JsonKey.EDIT_LINK), entity.getEditLink().getHref()); if (entity.isMediaEntity()) { jgen.writeStringField(version.getJsonName(ODataServiceVersion.JsonKey.MEDIA_READ_LINK), entity.getEditLink().getHref() + "/$value"); } } links(entity, jgen); for (Link link : entity.getMediaEditLinks()) { if (link.getTitle() == null) { jgen.writeStringField(version.getJsonName(ODataServiceVersion.JsonKey.MEDIA_EDIT_LINK), link.getHref()); } if (link.getInlineEntity() != null) { jgen.writeObjectField(link.getTitle(), link.getInlineEntity()); } if (link.getInlineEntitySet() != null) { jgen.writeArrayFieldStart(link.getTitle()); for (Entity subEntry : link.getInlineEntitySet().getEntities()) { jgen.writeObject(subEntry); } jgen.writeEndArray(); } } if (serverMode) { for (ODataOperation operation : entity.getOperations()) { jgen.writeObjectFieldStart( "#" + StringUtils.substringAfterLast(operation.getMetadataAnchor(), "#")); jgen.writeStringField(Constants.ATTR_TITLE, operation.getTitle()); jgen.writeStringField(Constants.ATTR_TARGET, operation.getTarget().toASCIIString()); jgen.writeEndObject(); } } jgen.writeEndObject(); }