Java Code Examples for com.fasterxml.jackson.core.JsonGenerator

The following examples show how to use com.fasterxml.jackson.core.JsonGenerator. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: kripton   Author: xcesco   File: Bean84B2BindMap.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int serializeOnJackson(Bean84B2 object, JsonGenerator jacksonSerializer) throws Exception {
  jacksonSerializer.writeStartObject();
  int fieldCount=0;

  // Serialized Field:

  // field columnString (mapped with "columnString")
  if (object.columnString!=null)  {
    fieldCount++;
    jacksonSerializer.writeStringField("columnString", object.columnString);
  }

  jacksonSerializer.writeEndObject();
  return fieldCount;
}
 
Example #2
Source Project: kripton   Author: xcesco   File: ThumbnailBindMap.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int serializeOnJacksonAsString(Thumbnail object, JsonGenerator jacksonSerializer) throws
    Exception {
  jacksonSerializer.writeStartObject();
  int fieldCount=0;

  // Serialized Field:

  // field height (mapped with "height")
  jacksonSerializer.writeStringField("height", PrimitiveUtils.writeLong(object.getHeight()));

  // field url (mapped with "url")
  if (object.getUrl()!=null)  {
    fieldCount++;
    jacksonSerializer.writeStringField("url", UrlUtils.write(object.getUrl()));
  }

  // field width (mapped with "width")
  jacksonSerializer.writeStringField("width", PrimitiveUtils.writeLong(object.getWidth()));

  jacksonSerializer.writeEndObject();
  return fieldCount;
}
 
Example #3
Source Project: lams   Author: lamsfoundation   File: BeanSerializer.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Main serialization method that will delegate actual output to
 * configured
 * {@link BeanPropertyWriter} instances.
 */
@Override
public final void serialize(Object bean, JsonGenerator gen, SerializerProvider provider)
    throws IOException
{
    if (_objectIdWriter != null) {
        gen.setCurrentValue(bean); // [databind#631]
        _serializeWithObjectId(bean, gen, provider, true);
        return;
    }
    gen.writeStartObject(bean);
    if (_propertyFilterId != null) {
        serializeFieldsFiltered(bean, gen, provider);
    } else {
        serializeFields(bean, gen, provider);
    }
    gen.writeEndObject();
}
 
Example #4
Source Project: kripton   Author: xcesco   File: PersonBindMap.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int serializeOnJackson(Person object, JsonGenerator jacksonSerializer) throws Exception {
  jacksonSerializer.writeStartObject();
  int fieldCount=0;

  // Serialized Field:

  // field age (mapped with "age")
  fieldCount++;
  jacksonSerializer.writeNumberField("age", object.age);

  // field id (mapped with "id")
  fieldCount++;
  jacksonSerializer.writeNumberField("id", object.id);

  // field name (mapped with "name")
  if (object.name!=null)  {
    fieldCount++;
    jacksonSerializer.writeStringField("name", object.name);
  }

  jacksonSerializer.writeEndObject();
  return fieldCount;
}
 
Example #5
Source Project: baleen   Author: dstl   File: AbstractJsonConsumer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Write annotation with features (including non-primitives)
 *
 * @param generator the generator
 * @param annotation the annotation
 * @param features the features
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void writeFS(JsonGenerator generator, FeatureStructure annotation, List<Feature> features)
    throws IOException {
  generator.writeObjectFieldStart("fields");
  for (Feature feature : features) {
    if (feature.getRange().isPrimitive()) {
      writePrimitive(generator, annotation, feature);
    } else if (feature.getRange().isArray()) {
      writeArray(generator, annotation, feature);
    } else {
      if ("uima.cas.AnnotationBase:sofa".equals(feature.getName())) {
        continue;
      }
      FeatureStructure featureValue = annotation.getFeatureValue(feature);
      if (featureValue != null) {
        generator.writeFieldName(feature.getShortName());
        writeFS(generator, featureValue);
      }
    }
  }
  generator.writeEndObject();
}
 
Example #6
Source Project: usergrid   Author: apache   File: ExportAdmins.java    License: Apache License 2.0 6 votes vote down vote up
private void saveDictionaries( JsonGenerator jg, AdminUserWriteTask task ) throws Exception {

            jg.writeFieldName( "dictionaries" );
            jg.writeStartObject();

            for (String dictionary : task.dictionariesByName.keySet() ) {

                Map<Object, Object> dict = task.dictionariesByName.get( dictionary );

                if (dict.isEmpty()) {
                    continue;
                }

                jg.writeFieldName( dictionary );

                jg.writeStartObject();

                for (Map.Entry<Object, Object> entry : dict.entrySet()) {
                    jg.writeFieldName( entry.getKey().toString() );
                    jg.writeObject( entry.getValue() );
                }

                jg.writeEndObject();
            }
            jg.writeEndObject();
        }
 
Example #7
Source Project: kripton   Author: xcesco   File: DeviceAccessTokenBindMap.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int serializeOnJackson(DeviceAccessToken object, JsonGenerator jacksonSerializer) throws
    Exception {
  jacksonSerializer.writeStartObject();
  int fieldCount=0;

  // Serialized Field:

  // field creationTime (mapped with "creationTime")
  fieldCount++;
  jacksonSerializer.writeNumberField("creationTime", object.getCreationTime());

  // field lastUsedTime (mapped with "lastUsedTime")
  fieldCount++;
  jacksonSerializer.writeNumberField("lastUsedTime", object.getLastUsedTime());

  jacksonSerializer.writeEndObject();
  return fieldCount;
}
 
Example #8
Source Project: presto   Author: prestosql   File: MapToJsonCast.java    License: Apache License 2.0 6 votes vote down vote up
@UsedByGeneratedCode
public static Slice toJson(ObjectKeyProvider provider, JsonGeneratorWriter writer, ConnectorSession session, Block block)
{
    try {
        Map<String, Integer> orderedKeyToValuePosition = new TreeMap<>();
        for (int i = 0; i < block.getPositionCount(); i += 2) {
            String objectKey = provider.getObjectKey(block, i);
            orderedKeyToValuePosition.put(objectKey, i + 1);
        }

        SliceOutput output = new DynamicSliceOutput(40);
        try (JsonGenerator jsonGenerator = createJsonGenerator(JSON_FACTORY, output)) {
            jsonGenerator.writeStartObject();
            for (Map.Entry<String, Integer> entry : orderedKeyToValuePosition.entrySet()) {
                jsonGenerator.writeFieldName(entry.getKey());
                writer.writeJsonValue(jsonGenerator, block, entry.getValue(), session);
            }
            jsonGenerator.writeEndObject();
        }
        return output.slice();
    }
    catch (IOException e) {
        throwIfUnchecked(e);
        throw new RuntimeException(e);
    }
}
 
Example #9
Source Project: splicer   Author: turn   File: TsdbResult.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(Tags tags, JsonGenerator jgen, SerializerProvider provider)
		throws IOException {
	if (tags.getTags() == null) {
		return;
	}

	jgen.writeStartObject();

	TreeMap<String, String> sorted = new TreeMap<>(tags.getTags());
	for (Map.Entry<String, String> e: sorted.entrySet()) {
		jgen.writeStringField(e.getKey(), e.getValue());
	}

	jgen.writeEndObject();
}
 
Example #10
Source Project: kripton   Author: xcesco   File: PersonBindMap.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int serializeOnJacksonAsString(Person object, JsonGenerator jacksonSerializer) throws
    Exception {
  jacksonSerializer.writeStartObject();
  int fieldCount=0;

  // Serialized Field:

  // field id (mapped with "id")
  jacksonSerializer.writeStringField("id", PrimitiveUtils.writeLong(object.id));

  // field name (mapped with "name")
  if (object.name!=null)  {
    fieldCount++;
    jacksonSerializer.writeStringField("name", object.name);
  }

  jacksonSerializer.writeEndObject();
  return fieldCount;
}
 
Example #11
Source Project: konker-platform   Author: KonkerLabs   File: MessagePackJsonConverter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ServiceResponse<byte[]> fromJson(String json) {

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        // read json
        ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());
        JsonNode node = objectMapper.readTree(json);

        // write message pack
        MessagePackFactory messagePackFactory = new MessagePackFactory();
        JsonGenerator jsonGenerator = messagePackFactory.createGenerator(bos);

        objectMapper.writeTree(jsonGenerator, node);
    } catch (IOException e) {
        LOGGER.error("Exception converting message pack to JSON", e);
        return ServiceResponseBuilder.<byte[]>error().build();
    }

    return ServiceResponseBuilder.<byte[]>ok().withResult(bos.toByteArray()).build();

}
 
Example #12
Source Project: aws-athena-query-federation   Author: awslabs   File: GetSplitsRequestSerDe.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doRequestSerialize(FederationRequest federationRequest, JsonGenerator jgen, SerializerProvider provider)
        throws IOException
{
    GetSplitsRequest getSplitsRequest = (GetSplitsRequest) federationRequest;

    jgen.writeFieldName(TABLE_NAME_FIELD);
    tableNameSerializer.serialize(getSplitsRequest.getTableName(), jgen, provider);

    jgen.writeFieldName(PARTITIONS_FIELD);
    blockSerializer.serialize(getSplitsRequest.getPartitions(), jgen, provider);

    writeStringArray(jgen, PARTITION_COLS_FIELD, getSplitsRequest.getPartitionCols());

    jgen.writeFieldName(CONSTRAINTS_FIELD);
    constraintsSerializer.serialize(getSplitsRequest.getConstraints(), jgen, provider);

    jgen.writeStringField(CONTINUATION_TOKEN_FIELD, getSplitsRequest.getContinuationToken());
}
 
Example #13
Source Project: kripton   Author: xcesco   File: ChannelTable.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * for attribute image serialization
 */
public static byte[] serializeImage(Image value) {
  if (value==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
    JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
    int fieldCount=0;
    if (value!=null)  {
      fieldCount++;
      imageBindMap.serializeOnJackson(value, jacksonSerializer);
    }
    jacksonSerializer.flush();
    return stream.toByteArray();
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example #14
Source Project: centraldogma   Author: line   File: TestAbsenceOperation.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
    gen.writeStartObject();
    gen.writeStringField("op", op);
    gen.writeStringField("path", path.toString());
    gen.writeEndObject();
}
 
Example #15
Source Project: nifi   Author: apache   File: PutElasticsearchHttpRecord.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
    generator.writeEndArray();
}
 
Example #16
Source Project: kripton   Author: xcesco   File: CharDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * for param serializer1 serialization
 */
private byte[] serializer1(char[] value) {
  if (value==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
    JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
    int fieldCount=0;
    jacksonSerializer.writeStartObject();
    if (value!=null)  {
      int n=value.length;
      char item;
      // write wrapper tag
      jacksonSerializer.writeFieldName("element");
      jacksonSerializer.writeStartArray();
      for (int i=0; i<n; i++) {
        item=value[i];
        jacksonSerializer.writeNumber(item);
      }
      jacksonSerializer.writeEndArray();
    }
    jacksonSerializer.writeEndObject();
    jacksonSerializer.flush();
    return stream.toByteArray();
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example #17
Source Project: olingo-odata4   Author: apache   File: ODataJsonSerializer.java    License: Apache License 2.0 5 votes vote down vote up
protected void writeComplexValue(final ServiceMetadata metadata,
    final EdmComplexType type, final List<Property> properties,
    final Set<List<String>> selectedPaths, final JsonGenerator json, 
    Set<List<String>> expandedPaths, Linked linked, ExpandOption expand, String complexPropName)
    throws IOException, SerializerException {

  if (null != expandedPaths) {
    for(List<String> paths : expandedPaths) {
      if (!paths.isEmpty() && paths.size() == 1) {
        expandedPaths = ExpandSelectHelper.getReducedExpandItemsPaths(expandedPaths, paths.get(0));
      }
    }
  }
  
  for (final String propertyName : type.getPropertyNames()) {
    final Property property = findProperty(propertyName, properties);
    if (selectedPaths == null || ExpandSelectHelper.isSelected(selectedPaths, propertyName)) {
      writeProperty(metadata, (EdmProperty) type.getProperty(propertyName), property,
          selectedPaths == null ? null : ExpandSelectHelper.getReducedSelectedPaths(selectedPaths, propertyName),
          json, expandedPaths, linked, expand);
    }
  }
  try {
    writeNavigationProperties(metadata, type, linked, expand, null, null, complexPropName, json);
  } catch (DecoderException e) {
    throw new SerializerException(IO_EXCEPTION_TEXT, e, SerializerException.MessageKeys.IO_EXCEPTION);
  }
}
 
Example #18
Source Project: warp10-platform   Author: senx   File: MetadataSerializer.java    License: Apache License 2.0 5 votes vote down vote up
public static void serializeMetadataFields(Metadata metadata, JsonGenerator gen) throws IOException {
  String name = metadata.getName();
  if (null == name) {
    name = "";
  }

  gen.writeStringField(FIELD_NAME, name);
  gen.writeObjectField(FIELD_LABELS, metadata.getLabels());
  gen.writeObjectField(FIELD_ATTRIBUTES, metadata.getAttributes());
  gen.writeNumberField(FIELD_LASTACTIVITY, metadata.getLastActivity());
}
 
Example #19
Source Project: kripton   Author: xcesco   File: Security47BindMap.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int serializeOnJackson(Security47 object, JsonGenerator jacksonSerializer) throws
    Exception {
  jacksonSerializer.writeStartObject();
  int fieldCount=0;

  // Serialized Field:

  // field authorizationToken (mapped with "authorizationToken")
  if (object.authorizationToken!=null)  {
    fieldCount++;
    jacksonSerializer.writeFieldName("authorizationToken");
    deviceAccessTokenBindMap.serializeOnJackson(object.authorizationToken, jacksonSerializer);
  }

  // field deviceUid (mapped with "deviceUid")
  if (object.deviceUid!=null)  {
    fieldCount++;
    jacksonSerializer.writeStringField("deviceUid", object.deviceUid);
  }

  // field fcmId (mapped with "fcmId")
  if (object.fcmId!=null)  {
    fieldCount++;
    jacksonSerializer.writeStringField("fcmId", object.fcmId);
  }

  // field userIdentity (mapped with "userIdentity")
  if (object.userIdentity!=null)  {
    fieldCount++;
    jacksonSerializer.writeFieldName("userIdentity");
    userIdentityBindMap.serializeOnJackson(object.userIdentity, jacksonSerializer);
  }

  jacksonSerializer.writeEndObject();
  return fieldCount;
}
 
Example #20
Source Project: spring-analysis-note   Author: Vip-Augus   File: Jackson2ObjectMapperBuilderTests.java    License: MIT License 5 votes vote down vote up
@Override
public void serialize(Integer value, JsonGenerator gen, SerializerProvider serializers)
		throws IOException {

	gen.writeStartObject();
	gen.writeNumberField("customid", value);
	gen.writeEndObject();
}
 
Example #21
Source Project: beam   Author: apache   File: MetricsHttpSink.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(MetricResult value, JsonGenerator gen, SerializerProvider provider)
    throws IOException {
  gen.writeStartObject();
  gen.writeObjectField("attempted", value.getAttempted());
  if (value.hasCommitted()) {
    gen.writeObjectField("committed", value.getCommitted());
  }
  keySerializer.inline(value.getKey(), gen, provider);
  gen.writeEndObject();
}
 
Example #22
Source Project: flowable-engine   Author: flowable   File: DateToStringSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Date tmpDate, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {

    if (tmpDate != null) {
        jsonGenerator.writeString(new DateTime(tmpDate).toString(isoFormatter));
    } else {
        jsonGenerator.writeNull();
    }
}
 
Example #23
Source Project: controller-advice-exception-handler   Author: nielsutrecht   File: ApplicationConfiguration.java    License: MIT License 5 votes vote down vote up
public JsonSerializer<LocalDate> localDateSerializer() {
    return new JsonSerializer<LocalDate>() {
        @Override
        public void serialize(LocalDate localDate, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
            jsonGenerator.writeString(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
        }
    };
}
 
Example #24
Source Project: nakadi   Author: zalando   File: NakadiMetricsModule.java    License: MIT License 5 votes vote down vote up
@Override
public void serialize(final Counter counter,
                      final JsonGenerator json,
                      final SerializerProvider provider) throws IOException {
    json.writeStartObject();
    json.writeNumberField("count", counter.getCount());
    json.writeEndObject();
}
 
Example #25
Source Project: aws-athena-query-federation   Author: awslabs   File: ListTablesRequestSerDe.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doRequestSerialize(FederationRequest federationRequest, JsonGenerator jgen, SerializerProvider provider)
        throws IOException
{
    ListTablesRequest listTablesRequest = (ListTablesRequest) federationRequest;

    jgen.writeStringField(SCHEMA_NAME_FIELD, listTablesRequest.getSchemaName());
}
 
Example #26
Source Project: presto   Author: prestosql   File: JsonEventClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T> void postEvent(T event)
{
    try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        JsonGenerator generator = factory.createGenerator(buffer, JsonEncoding.UTF8);
        serializer.serialize(event, generator);
        out.println(buffer.toString().trim());
    }
    catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #27
Source Project: kripton   Author: xcesco   File: BeanTable.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * for attribute valueMapStringBean serialization
 */
public static byte[] serializeValueMapStringBean(Map<String, Bean> value) {
  if (value==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
    JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
    jacksonSerializer.writeStartObject();
    int fieldCount=0;
    if (value!=null)  {
      fieldCount++;
      // write wrapper tag
      if (value.size()>0) {
        jacksonSerializer.writeFieldName("element");
        jacksonSerializer.writeStartArray();
        for (Map.Entry<String, Bean> item: value.entrySet()) {
          jacksonSerializer.writeStartObject();
          jacksonSerializer.writeStringField("key", item.getKey());
          if (item.getValue()==null) {
            jacksonSerializer.writeNullField("value");
          } else {
            jacksonSerializer.writeFieldName("value");
            beanBindMap.serializeOnJackson(item.getValue(), jacksonSerializer);
          }
          jacksonSerializer.writeEndObject();
        }
        jacksonSerializer.writeEndArray();
      } else {
        jacksonSerializer.writeNullField("element");
      }
    }
    jacksonSerializer.writeEndObject();
    jacksonSerializer.flush();
    return stream.toByteArray();
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example #28
Source Project: calcite   Author: apache   File: DruidQuery.java    License: Apache License 2.0 5 votes vote down vote up
protected static void writeArray(JsonGenerator generator, List<?> elements)
    throws IOException {
  generator.writeStartArray();
  for (Object o : elements) {
    writeObject(generator, o);
  }
  generator.writeEndArray();
}
 
Example #29
Source Project: kripton   Author: xcesco   File: CharDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * for param serializer2 serialization
 */
private byte[] serializer2(List<Short> value) {
  if (value==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
    JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
    int fieldCount=0;
    jacksonSerializer.writeStartObject();
    if (value!=null)  {
      int n=value.size();
      Short item;
      // write wrapper tag
      jacksonSerializer.writeFieldName("element");
      jacksonSerializer.writeStartArray();
      for (int i=0; i<n; i++) {
        item=value.get(i);
        if (item==null) {
          jacksonSerializer.writeNull();
        } else {
          jacksonSerializer.writeNumber(item);
        }
      }
      jacksonSerializer.writeEndArray();
    }
    jacksonSerializer.writeEndObject();
    jacksonSerializer.flush();
    return stream.toByteArray();
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example #30
Source Project: agrest   Author: agrestio   File: ISOOffsetDateTimeEncoder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected boolean encodeNonNullObject(Object object, JsonGenerator out) throws IOException {
    OffsetDateTime dateTime = (OffsetDateTime) object;
    String formatted = DateTimeFormatters.isoOffsetDateTime().format(dateTime);
    out.writeObject(formatted);
    return true;
}