com.fasterxml.jackson.core.JsonGenerator Java Examples

The following examples show how to use com.fasterxml.jackson.core.JsonGenerator. 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 File: AbstractJsonConsumer.java    From baleen with 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 #2
Source File: ThumbnailBindMap.java    From kripton with 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 File: Bean84B2BindMap.java    From kripton with 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 #4
Source File: ChannelTable.java    From kripton with 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 #5
Source File: GetSplitsRequestSerDe.java    From aws-athena-query-federation with 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 #6
Source File: MessagePackJsonConverter.java    From konker-platform with 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 #7
Source File: BeanSerializer.java    From lams with 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 #8
Source File: PersonBindMap.java    From kripton with 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 #9
Source File: PersonBindMap.java    From kripton with 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 #10
Source File: TsdbResult.java    From splicer with 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 #11
Source File: MapToJsonCast.java    From presto with 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 #12
Source File: DeviceAccessTokenBindMap.java    From kripton with 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 #13
Source File: ExportAdmins.java    From usergrid with 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 #14
Source File: BeanAsArraySerializer.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
public void serializeContents(Object value, JsonGenerator jgen, SerializerProvider provider)
    throws IOException
{
    JsonPropertyOrder order = value.getClass().getAnnotation(JsonPropertyOrder.class);
    String[] propOrder = (order == null) ? null : order.value();

    if (propOrder == null) {
        throw new IllegalStateException("Bean must declare JsonPropertyOrder!");
    }

    if (propOrder.length == 0) {
        return;
    }

    int i = 0;
    try {
        do {
            Field field = value.getClass().getDeclaredField(propOrder[i]);
            ReflectionUtils.makeAccessible(field);
            Object elem = field.get(value);
            if (elem == null) {
                provider.defaultSerializeNull(jgen);
            }
            else {
                Class<?> cc = elem.getClass();
                JsonSerializer<Object> serializer = provider.findValueSerializer(cc, null);
                serializer.serialize(elem, jgen, provider);
            }
            ++i;
        }
        while (i < propOrder.length);
    }
    catch (Exception e) {
        // [JACKSON-55] Need to add reference information
        wrapAndThrow(provider, e, value, i);
    }
}
 
Example #15
Source File: NullPartitionKeyComponent.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
@Override
public void JsonEncode(JsonGenerator writer) {
    try {
        writer.writeObject(null);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #16
Source File: ImpExtWriter.java    From openrtb-doubleclick with Apache License 2.0 5 votes vote down vote up
private void writeExcludedCreative(ExcludedCreative exCreat, JsonGenerator gen)
    throws IOException {
  gen.writeStartObject();
  writeExcludedCreativeFields(exCreat, gen);
  gen.writeEndObject();
  gen.flush();
}
 
Example #17
Source File: BindAppPreferences.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for attribute stringArray serialization
 */
protected String serializeStringArray(String[] 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++;
      int n=value.length;
      String item;
      // write wrapper tag
      jacksonSerializer.writeFieldName("stringArray");
      jacksonSerializer.writeStartArray();
      for (int i=0; i<n; i++) {
        item=value[i];
        if (item==null) {
          jacksonSerializer.writeNull();
        } else {
          jacksonSerializer.writeString(item);
        }
      }
      jacksonSerializer.writeEndArray();
    }
    jacksonSerializer.writeEndObject();
    jacksonSerializer.flush();
    return stream.toString();
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example #18
Source File: TransactionJsonService.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@GET(path = "/backend/transaction/queries", permission = "agent:transaction:queries")
String getQueries(@BindAgentRollupId String agentRollupId,
        @BindRequest TransactionDataRequest request) throws Exception {
    AggregateQuery query = toQuery(request, DataKind.QUERY);
    QueryCollector queryCollector =
            transactionCommonService.getMergedQueries(agentRollupId, query);
    List<MutableQuery> queries = queryCollector.getSortedAndTruncatedQueries();
    if (queries.isEmpty() && fallBackToLargestAggregates(query)) {
        // fall back to largest aggregates in case expiration settings have recently changed
        query = withLargestRollupLevel(query);
        queryCollector = transactionCommonService.getMergedQueries(agentRollupId, query);
        queries = queryCollector.getSortedAndTruncatedQueries();
        if (ignoreFallBackData(query, queryCollector.getLastCaptureTime())) {
            // this is probably data from before the requested time period
            queries = ImmutableList.of();
        }
    }
    List<Query> queryList = Lists.newArrayList();
    for (MutableQuery loopQuery : queries) {
        queryList.add(ImmutableQuery.builder()
                .queryType(loopQuery.getType())
                .truncatedQueryText(loopQuery.getTruncatedText())
                .fullQueryTextSha1(loopQuery.getFullTextSha1())
                .totalDurationNanos(loopQuery.getTotalDurationNanos())
                .executionCount(loopQuery.getExecutionCount())
                .totalRows(loopQuery.hasTotalRows() ? loopQuery.getTotalRows() : null)
                .build());
    }
    if (queryList.isEmpty() && aggregateRepository.shouldHaveQueries(agentRollupId, query)) {
        return "{\"overwritten\":true}";
    }
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeObject(queryList);
    } finally {
        jg.close();
    }
    return sb.toString();
}
 
Example #19
Source File: NodeCalc.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
static void writeJson(NodeCalc node, JsonGenerator generator) {
    try {
        generator.writeStartObject();
        node.writeJson(generator);
        generator.writeEndObject();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #20
Source File: InetSocketAddressSerializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void serializeWithType(InetSocketAddress value, JsonGenerator g,
        SerializerProvider provider, TypeSerializer typeSer) throws IOException
{
    // Better ensure we don't use specific sub-classes...
    WritableTypeId typeIdDef = typeSer.writeTypePrefix(g,
            typeSer.typeId(value, InetSocketAddress.class, JsonToken.VALUE_STRING));
    serialize(value, g, provider);
    typeSer.writeTypeSuffix(g, typeIdDef);
}
 
Example #21
Source File: OpenRtbJsonUtils.java    From openrtb with Apache License 2.0 5 votes vote down vote up
/**
 * Writes a string array if not empty.
 */
public static void writeStrings(String fieldName, List<String> data, JsonGenerator gen)
    throws IOException {
  if (!data.isEmpty()) {
    gen.writeArrayFieldStart(fieldName);
    for (String d : data) {
      gen.writeString(d);
    }
    gen.writeEndArray();
  }
}
 
Example #22
Source File: ArrayOrString.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private void writeArray(ArrayOrString value, JsonGenerator jgen) throws IOException {
  jgen.writeStartArray(value.getArrayVal().size());
  for (String n : value.getArrayVal()) {
    jgen.writeString(n);
  }
  jgen.writeEndArray();
}
 
Example #23
Source File: MetricsElasticsearchModule.java    From oneops with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(JsonCounter counter,
                      JsonGenerator json,
                      SerializerProvider provider) throws IOException {
    json.writeStartObject();
    json.writeStringField("name", counter.name());
    json.writeObjectField(timestampFieldname, counter.timestampAsDate());
    json.writeNumberField("count", counter.value().getCount());
    addOneOpsMetadata(json);
    json.writeEndObject();
}
 
Example #24
Source File: LoggerSettingsBindMap.java    From kripton with Apache License 2.0 5 votes vote down vote up
@Override
public int serializeOnJackson(LoggerSettings object, JsonGenerator jacksonSerializer) throws
    Exception {
  jacksonSerializer.writeStartObject();
  int fieldCount=0;

  // Serialized Field:

  // field appenders (mapped with "appenders")
  if (object.appenders!=null)  {
    fieldCount++;
    int n=object.appenders.size();
    LoggerAppenderSettings item;
    // write wrapper tag
    jacksonSerializer.writeFieldName("appenders");
    jacksonSerializer.writeStartArray();
    for (int i=0; i<n; i++) {
      item=object.appenders.get(i);
      if (item==null) {
        jacksonSerializer.writeNull();
      } else {
        loggerAppenderSettingsBindMap.serializeOnJackson(item, jacksonSerializer);
      }
    }
    jacksonSerializer.writeEndArray();
  }

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

  jacksonSerializer.writeEndObject();
  return fieldCount;
}
 
Example #25
Source File: PipelineOptionsFactoryTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(
    JacksonIncompatible jacksonIncompatible,
    JsonGenerator jsonGenerator,
    SerializerProvider serializerProvider)
    throws IOException, JsonProcessingException {
  jsonGenerator.writeString(jacksonIncompatible.value);
}
 
Example #26
Source File: RecordBase.java    From yql-plus with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    for (String fieldName : getFieldNames()) {
        Object value = get(fieldName);
        if (value != null) {
            provider.defaultSerializeField(fieldName, value, jgen);
        }
    }
    jgen.writeEndObject();
}
 
Example #27
Source File: TestAbsenceOperation.java    From centraldogma with 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 #28
Source File: EnumBaseSerializer.java    From java-master with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(EnumBase value, JsonGenerator gen, SerializerProvider serializers)
        throws IOException {
    if (value != null) {
        gen.writeNumber(value.getCode());
    } else {
        gen.writeNull();
    }
}
 
Example #29
Source File: IndexedListSerializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void serializeTypedContents(List<?> value, JsonGenerator jgen, SerializerProvider provider)
    throws IOException
{
    final int len = value.size();
    if (len == 0) {
        return;
    }
    int i = 0;
    try {
        final TypeSerializer typeSer = _valueTypeSerializer;
        PropertySerializerMap serializers = _dynamicSerializers;
        for (; i < len; ++i) {
            Object elem = value.get(i);
            if (elem == null) {
                provider.defaultSerializeNull(jgen);
            } else {
                Class<?> cc = elem.getClass();
                JsonSerializer<Object> serializer = serializers.serializerFor(cc);
                if (serializer == null) {
                    // To fix [JACKSON-508]
                    if (_elementType.hasGenericTypes()) {
                        serializer = _findAndAddDynamic(serializers,
                                provider.constructSpecializedType(_elementType, cc), provider);
                    } else {
                        serializer = _findAndAddDynamic(serializers, cc, provider);
                    }
                    serializers = _dynamicSerializers;
                }
                serializer.serializeWithType(elem, jgen, provider, typeSer);
            }
        }
    } catch (Exception e) {
        // [JACKSON-55] Need to add reference information
        wrapAndThrow(provider, e, value, i);
    }
}
 
Example #30
Source File: Bean87A_7BindMap.java    From kripton with Apache License 2.0 5 votes vote down vote up
@Override
public int serializeOnJacksonAsString(Bean87A_7 object, JsonGenerator jacksonSerializer) throws
    Exception {
  jacksonSerializer.writeStartObject();
  int fieldCount=0;

  // Serialized Field:

  // field attributeString (mapped with "attributeString")
  if (object.attributeString!=null)  {
    fieldCount++;
    // using type adapter bind.feature.typeadapter.kripton87.StringInverterTypeAdapter
    jacksonSerializer.writeStringField("attributeString", TypeAdapterUtils.toData(StringInverterTypeAdapter.class, object.attributeString));
  }

  // field dataString (mapped with "dataString")
  if (object.dataString!=null)  {
    fieldCount++;
    // using type adapter bind.feature.typeadapter.kripton87.StringInverterTypeAdapter
    jacksonSerializer.writeStringField("dataString", TypeAdapterUtils.toData(StringInverterTypeAdapter.class, object.dataString));
  }

  // field elementString (mapped with "elementString")
  if (object.elementString!=null)  {
    fieldCount++;
    // using type adapter bind.feature.typeadapter.kripton87.StringInverterTypeAdapter
    jacksonSerializer.writeStringField("elementString", TypeAdapterUtils.toData(StringInverterTypeAdapter.class, object.elementString));
  }

  jacksonSerializer.writeEndObject();
  return fieldCount;
}