Java Code Examples for com.fasterxml.jackson.databind.SerializerProvider

The following examples show how to use com.fasterxml.jackson.databind.SerializerProvider. 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: syncope   Source File: SyncTokenSerializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(final SyncToken source, final JsonGenerator jgen, final SerializerProvider sp)
        throws IOException {

    jgen.writeStartObject();

    jgen.writeFieldName("value");

    if (source.getValue() == null) {
        jgen.writeNull();
    } else if (source.getValue() instanceof Boolean) {
        jgen.writeBoolean((Boolean) source.getValue());
    } else if (source.getValue() instanceof Double) {
        jgen.writeNumber((Double) source.getValue());
    } else if (source.getValue() instanceof Long) {
        jgen.writeNumber((Long) source.getValue());
    } else if (source.getValue() instanceof Integer) {
        jgen.writeNumber((Integer) source.getValue());
    } else if (source.getValue() instanceof byte[]) {
        jgen.writeString(Base64.getEncoder().encodeToString((byte[]) source.getValue()));
    } else {
        jgen.writeString(source.getValue().toString());
    }

    jgen.writeEndObject();
}
 
Example 2
Source Project: roboconf-platform   Source File: JSonBindingUtils.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(
		Diagnostic diag,
		JsonGenerator generator,
		SerializerProvider provider )
throws IOException {

	generator.writeStartObject();
	if( diag.getInstancePath() != null )
		generator.writeStringField( DIAG_PATH, diag.getInstancePath());

	generator.writeArrayFieldStart( DIAG_DEPENDENCIES );
	for( DependencyInformation info : diag.getDependenciesInformation())
		generator.writeObject( info );
	generator.writeEndArray();

	generator.writeEndObject();
}
 
Example 3
@Test
public void SmartErrorCodePropertyWriter_serializeAsField_still_works_for_non_Error_objects() throws Exception {
    // given
    final SmartErrorCodePropertyWriter secpw = new SmartErrorCodePropertyWriter(mock(BeanPropertyWriter.class));

    // when
    Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            secpw.serializeAsField(new Object(), mock(JsonGenerator.class), mock(SerializerProvider.class));
        }
    });

    // then
    // We expect a NPE because mocking a base BeanPropertyWriter is incredibly difficult and not worth the effort.
    assertThat(ex).isInstanceOf(NullPointerException.class);
}
 
Example 4
Source Project: crnk-framework   Source File: LinksInformationSerializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(LinksInformation value, JsonGenerator gen, SerializerProvider serializers)
		throws IOException {

	gen.writeStartObject();

	BeanInformation info = BeanInformation.get(value.getClass());

	for (String attrName : info.getAttributeNames()) {
		BeanAttributeInformation attribute = info.getAttribute(attrName);
		Object objLinkValue = attribute.getValue(value);
		String name = attribute.getJsonName();
		Link linkValue = objLinkValue instanceof String ? new DefaultLink((String) objLinkValue) : (Link) objLinkValue;
		if (linkValue != null) {
			if (!serializeLinksAsObjects && !shouldSerializeLink(linkValue)) { // Return a simple String link
				gen.writeStringField(name, linkValue.getHref());
			} else {
				gen.writeObjectField(name, linkValue);
			}
		}
	}

	gen.writeEndObject();

}
 
Example 5
Source Project: datacollector   Source File: ExtendedMeterSerializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(ExtendedMeter meter, JsonGenerator jgen, SerializerProvider provider) throws IOException {
  jgen.writeStartObject();
  jgen.writeNumberField("count", meter.getCount());
  jgen.writeNumberField("m1_rate", meter.getOneMinuteRate() * this.rateFactor);
  jgen.writeNumberField("m5_rate", meter.getFiveMinuteRate() * this.rateFactor);
  jgen.writeNumberField("m15_rate", meter.getFifteenMinuteRate() * this.rateFactor);
  jgen.writeNumberField("m30_rate", meter.getThirtyMinuteRate() * this.rateFactor);
  jgen.writeNumberField("h1_rate", meter.getOneHourRate() * this.rateFactor);
  jgen.writeNumberField("h6_rate", meter.getSixHourRate() * this.rateFactor);
  jgen.writeNumberField("h12_rate", meter.getTwelveHourRate() * this.rateFactor);
  jgen.writeNumberField("h24_rate", meter.getTwentyFourHourRate() * this.rateFactor);
  jgen.writeNumberField("mean_rate", meter.getMeanRate() * this.rateFactor);
  jgen.writeStringField("units", this.rateUnit);
  jgen.writeEndObject();
}
 
Example 6
Source Project: dremio-oss   Source File: JSONUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static <T1, T2> SimpleModule newWrappingModule(final Class<T1> wrapped, final Class<T2> wrapper, final Converter<T1, T2> converter) {
  SimpleModule module = new SimpleModule();
  module.addDeserializer(wrapper, new JsonDeserializer<T2>() {
    @Override
    public T2 deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
      return converter.convert(ctxt.readValue(p, wrapped));
    }
  });
  module.addSerializer(wrapper, new JsonSerializer<T2>() {
    @Override
    public void serialize(T2 value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
      serializers.defaultSerializeValue(converter.revert(value), gen);
    }
  });
  return module;
}
 
Example 7
@SuppressWarnings("RedundantThrows") // May throw IOException from inside lambda
@Override
protected void serializeEntries(ObjectCharMap<K> value, JsonGenerator gen, SerializerProvider serializers)
        throws IOException {
    value.forEachKeyValue((k, v) -> {
        try {
            _serializeKey(k, gen, serializers);
            /* if !(char|boolean value) //
            gen.writeNumber(v);
            /* elif char value */
            gen.writeString(new char[]{v}, 0, 1);
            /* elif boolean value //
            gen.writeBoolean(v);
            // endif */
        } catch (IOException e) {
            rethrowUnchecked(e);
        }
    });
}
 
Example 8
Source Project: beakerx   Source File: AreaSerializer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(Area area, JsonGenerator jgen, SerializerProvider sp)
    throws IOException, JsonProcessingException {

  jgen.writeStartObject();

  super.serialize(area, jgen, sp);

  if (area.getColor() instanceof Color) {
    jgen.writeObjectField("color", area.getColor());
  }
  if (area.getInterpolation() != null) {
    jgen.writeObjectField("interpolation", area.getInterpolation());
  }
  jgen.writeEndObject();
}
 
Example 9
Source Project: lams   Source File: InetAddressSerializer.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void serialize(InetAddress value, JsonGenerator g, SerializerProvider provider) throws IOException
{
    String str;

    if (_asNumeric) { // since 2.9
        str = value.getHostAddress();
    } else {
        // Ok: get textual description; choose "more specific" part
        str = value.toString().trim();
        int ix = str.indexOf('/');
        if (ix >= 0) {
            if (ix == 0) { // missing host name; use address
                str = str.substring(1);
            } else { // otherwise use name
                str = str.substring(0, ix);
            }
        }
    }
    g.writeString(str);
}
 
Example 10
@Override
public void serialize(DataArrayResult value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
    gen.writeStartObject();
    long count = value.getCount();
    if (count >= 0) {
        gen.writeNumberField(AT_IOT_COUNT, count);
    }
    String nextLink = value.getNextLink();
    if (nextLink != null) {
        gen.writeStringField(AT_IOT_NEXT_LINK, nextLink);
    }

    gen.writeFieldName("value");
    gen.writeObject(value.getValue());
    gen.writeEndObject();
}
 
Example 11
Source Project: caravan   Source File: AbstractBeanSerializer.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public final void serialize(Object bean, JsonGenerator gen, SerializerProvider provider)
    throws IOException {
  // replace field of java class with message of protobuf
  bean = convertBeanToSerialize(bean);

  if(bean instanceof List) {
    for(Object ele : (List)bean) {
      gen.writeStartObject(bean);
      serializeFields(ele, gen, provider);
      gen.writeEndObject();
    }
  } else {
    gen.writeStartObject(bean);
    serializeFields(bean, gen, provider);
    gen.writeEndObject();
  }
}
 
Example 12
Source Project: dremio-oss   Source File: DatasetFieldSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(List<Field> fields, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
  jsonGenerator.writeStartArray();

  for (Field field: fields) {
    APIFieldDescriber.FieldDescriber describer = new APIFieldDescriber.FieldDescriber(jsonGenerator, field, false);
    field.getType().accept(describer);
  }

  jsonGenerator.writeEndArray();
}
 
Example 13
Source Project: irontest   Source File: OracleTIMESTAMPTZSerializer.java    License: Apache License 2.0 5 votes vote down vote up
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
    String result = null;
    Method method = null;
    try {
        //  TIMESTAMPTZ.toJdbc() always returns null as there is no JDBC representation for Oracle TIMESTAMPTZ
        method = clazz.getDeclaredMethod("stringValue", Connection.class);
        result = (String) method.invoke(value, new Object[] { null });
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    gen.writeString(result);
}
 
Example 14
Source Project: caravan   Source File: XMLGregorianCalendarSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("all")
public void serialize(XMLGregorianCalendar value, JsonGenerator gen, SerializerProvider provider) throws IOException {
    if (value == null) {
        gen.writeNull();
        return;
    }

    gen.writeString(_serializer.serialize(value.toGregorianCalendar()));
}
 
Example 15
Source Project: seldon-server   Source File: JsonDateSerialiser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
        throws IOException {

    String formattedDate = dateFormat.format(date);

    gen.writeString(formattedDate);
}
 
Example 16
Source Project: mobilecloud-15   Source File: ResourcesMapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Resources value, JsonGenerator jgen,
		SerializerProvider provider) throws IOException,
		JsonProcessingException {
	// Extracted the actual data inside of the Resources object
	// that we care about (e.g., the list of Video objects)
	Object content = value.getContent();
	// Instead of all of the Resources member variables, etc.
	// Just mashall the actual content (Videos) into the JSON
	JsonSerializer<Object> s = provider.findValueSerializer(
			content.getClass(), null);
	s.serialize(content, jgen, provider);
}
 
Example 17
@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 18
Source Project: centraldogma   Source 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 19
@Override
public void serialize(APIQuota apiQuota, JsonGenerator jgen, SerializerProvider provider) throws IOException {
	// Set everything to null we want to have exported
	apiQuota.setDescription(null);
	apiQuota.setId(null);
	apiQuota.setName(null);
	apiQuota.setSystem(null);
	apiQuota.setType(null);
	for(QuotaRestriction restriction : apiQuota.getRestrictions()) {
		restriction.setApi(null );
	}
	defaultSerializer.serialize(apiQuota, jgen, provider);
}
 
Example 20
Source Project: syndesis   Source File: Mixed.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(final Mixed mixed, final JsonGenerator gen, final SerializerProvider serializers)
    throws IOException, JsonProcessingException {
    gen.writeStartObject();

    for (final Object part : mixed.parts) {
        serializers.defaultSerializeValue(part, new EnclosedJsonGenerator(gen));
    }

    gen.writeEndObject();
}
 
Example 21
@Override
public void serialize(final LeafEvent ev,
                      final JsonGenerator jgen,
                      final SerializerProvider provider)
throws IOException {
  jgen.writeNumber(ev.getValue());
}
 
Example 22
Source Project: ovsdb   Source File: OvsdbSetSerializer.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void serialize(OvsdbSet<?> set, JsonGenerator generator,
    SerializerProvider provider) throws IOException {
    generator.writeStartArray();
    generator.writeString("set");
    generator.writeStartArray();
    Set<?> javaSet = set.delegate();
    for (Object setObject : javaSet) {
        generator.writeObject(setObject);
    }
    generator.writeEndArray();
    generator.writeEndArray();
}
 
Example 23
Source Project: lams   Source File: ToStringSerializer.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Default implementation will write type prefix, call regular serialization
 * method (since assumption is that value itself does not need JSON
 * Array or Object start/end markers), and then write type suffix.
 * This should work for most cases; some sub-classes may want to
 * change this behavior.
 */
@Override
public void serializeWithType(Object value, JsonGenerator g, SerializerProvider provider,
        TypeSerializer typeSer)
    throws IOException
{
    WritableTypeId typeIdDef = typeSer.writeTypePrefix(g,
            typeSer.typeId(value, JsonToken.VALUE_STRING));
    serialize(value, g, provider);
    typeSer.writeTypeSuffix(g, typeIdDef);
}
 
Example 24
Source Project: cloudstack   Source File: UriSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(String id, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    jgen.writeStringField("id", id);
    jgen.writeFieldName("uri");
    jgen.writeString(buildUri(_annotation.clazz(), _annotation.method(), id));
    jgen.writeEndObject();
}
 
Example 25
Source Project: lams   Source File: TokenBufferSerializer.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Implementing typed output for contents of a TokenBuffer is very tricky,
 * since we do not know for sure what its contents might look like (or, rather,
 * we do know when serializing, but not necessarily when deserializing!)
 * One possibility would be to check the current token, and use that to
 * determine if we would output JSON Array, Object or scalar value.
 *<p>
 * Note that we just claim it is scalar; this should work ok and is simpler
 * than doing introspection on both serialization and deserialization.
 */
@Override
public final void serializeWithType(TokenBuffer value, JsonGenerator g,
        SerializerProvider provider, TypeSerializer typeSer) throws IOException
{
    // 28-Jun-2017, tatu: As per javadoc, not sure what to report as likely shape. Could
    //    even look into first actual token inside... but, for now let's keep it simple
    WritableTypeId typeIdDef = typeSer.writeTypePrefix(g,
            typeSer.typeId(value, JsonToken.VALUE_EMBEDDED_OBJECT));
    serialize(value, g, provider);
    typeSer.writeTypeSuffix(g, typeIdDef);
}
 
Example 26
@Override
public void serialize(
        Struct struct,
        JsonGenerator generator,
        SerializerProvider serializerProvider
) throws IOException {
  writeMap(FIELDS_FIELD, struct.getField(FIELDS_FIELD), generator, serializerProvider);
}
 
Example 27
public ConfigDefSerializationModule() {
  super();
  addSerializer(Password.class, new Serializer());
  addDeserializer(Password.class, new Deserializer());
  addSerializer(ConfigDef.Validator.class, new JsonSerializer<ConfigDef.Validator>() {
    @Override
    public void serialize(ConfigDef.Validator validator, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
      jsonGenerator.writeString(validator.toString());
    }
  });
}
 
Example 28
Source Project: nakadi   Source File: NakadiMetricsModule.java    License: MIT License 5 votes vote down vote up
@Override
public void serialize(final MetricRegistry registry,
                      final JsonGenerator json,
                      final SerializerProvider provider) throws IOException {
    json.writeStartObject();
    json.writeStringField("version", VERSION.toString());
    json.writeObjectField("gauges", registry.getGauges(filter));
    json.writeObjectField("counters", registry.getCounters(filter));
    json.writeObjectField("histograms", registry.getHistograms(filter));
    json.writeObjectField("meters", registry.getMeters(filter));
    json.writeObjectField("timers", registry.getTimers(filter));
    json.writeEndObject();
}
 
Example 29
Source Project: botbuilder-java   Source File: ByteArraySerializer.java    License: MIT License 5 votes vote down vote up
@Override
public void serialize(Byte[] value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
    byte[] bytes = new byte[value.length];
    for (int i = 0; i < value.length; i++) {
        bytes[i] = value[i];
    }
    jgen.writeBinary(bytes);
}
 
Example 30
public CustomSerializer() {
  addSerializer(Custom.class, new JsonSerializer<Custom>() {

    @Override
    public void serialize(Custom custom, JsonGenerator jgen, SerializerProvider provider) throws IOException {
      jgen.writeNumber(custom.getValue());
    }
  });
}