com.fasterxml.jackson.databind.SerializerProvider Java Examples

The following examples show how to use com.fasterxml.jackson.databind.SerializerProvider. 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: DataArrayResultSerializer.java    From FROST-Server with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #2
Source File: AbstractBeanSerializer.java    From caravan with 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 #3
Source File: ExtendedMeterSerializer.java    From datacollector with 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 #4
Source File: InetAddressSerializer.java    From lams with 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 #5
Source File: SyncTokenSerializer.java    From syncope with 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 #6
Source File: AreaSerializer.java    From beakerx with 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 #7
Source File: RefPrimitiveMapSerializers.java    From jackson-datatypes-collections with Apache License 2.0 6 votes vote down vote up
@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 File: LinksInformationSerializer.java    From crnk-framework with 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 #9
Source File: JSONUtil.java    From dremio-oss with 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 #10
Source File: JsonUtilWithDefaultErrorContractDTOSupportTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: JSonBindingUtils.java    From roboconf-platform with 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 #12
Source File: PrepareSerializer.java    From simulacron with Apache License 2.0 5 votes vote down vote up
@Override
public void serializeMessage(
    Prepare prepare, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
    throws IOException {
  jsonGenerator.writeObjectField("query", prepare.cqlQuery);
  jsonGenerator.writeObjectField("keyspace", prepare.keyspace);
}
 
Example #13
Source File: ResourcesMapper.java    From mobilecloud-15 with 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 #14
Source File: OvsdbSetSerializer.java    From ovsdb with 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 #15
Source File: ToStringSerializer.java    From lams with 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 #16
Source File: UriSerializer.java    From cloudstack with 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 #17
Source File: OptionValueSerializer.java    From microprofile-starter with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(OptionValue optionValue, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
        throws IOException {
    if (optionValue.isMultipleValues()) {
        serializerProvider.defaultSerializeValue(optionValue.getValues(), jsonGenerator);
    } else {
        jsonGenerator.writeString(optionValue.getSingleValue());
    }
}
 
Example #18
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 #19
Source File: CategoryBarsSerializer.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(CategoryBars categoryBars,
                      JsonGenerator jgen,
                      SerializerProvider provider) throws
                                                   IOException,
                                                   JsonProcessingException {
  jgen.writeStartObject();

  super.serialize(categoryBars, jgen, provider);

  if (categoryBars.getBases() != null) {
    jgen.writeObjectField("bases", categoryBars.getBases());
  } else {
    jgen.writeObjectField("base", categoryBars.getBase());
  }
  if (categoryBars.getWidths() != null) {
    jgen.writeObjectField("widths", categoryBars.getWidths());
  } else {
    jgen.writeObjectField("width", categoryBars.getWidth());
  }
  if (categoryBars.getOutlineColors() != null) {
    jgen.writeObjectField("outline_colors", categoryBars.getOutlineColors());
  } else {
    jgen.writeObjectField("outline_color", categoryBars.getOutlineColor());
  }
  if (categoryBars.getFills() != null) {
    jgen.writeObjectField("fills", categoryBars.getFills());
  } else {
    jgen.writeObjectField("fill", categoryBars.getFill());
  }
  if (categoryBars.getDrawOutlines() != null) {
    jgen.writeObjectField("outlines", categoryBars.getDrawOutlines());
  } else {
    jgen.writeObjectField("outline", categoryBars.getDrawOutline());
  }

  jgen.writeObjectField("labelPosition", categoryBars.getLabelPosition());

  jgen.writeEndObject();
}
 
Example #20
Source File: TokenBufferSerializer.java    From lams with 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 #21
Source File: StructSerializer.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(
        Struct struct,
        JsonGenerator generator,
        SerializerProvider serializerProvider
) throws IOException {
  writeMap(FIELDS_FIELD, struct.getField(FIELDS_FIELD), generator, serializerProvider);
}
 
Example #22
Source File: ConfigDefSerializationModule.java    From connect-utils with Apache License 2.0 5 votes vote down vote up
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 #23
Source File: NakadiMetricsModule.java    From nakadi with 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 #24
Source File: ByteArraySerializer.java    From botbuilder-java with 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 #25
Source File: TestSerializer.java    From beakerx with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(Object v, JsonGenerator jgen, SerializerProvider provider)
    throws IOException, JsonProcessingException {
  synchronized(v) {
    jgen.writeStartObject();
    jgen.writeStringField("type",  "test");
    jgen.writeObjectField("value", v);
    jgen.writeEndObject();
  }
}
 
Example #26
Source File: ImgJsonSerializer.java    From mall4j with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
    if (StrUtil.isBlank(value)) {
        gen.writeString(StrUtil.EMPTY);
        return;
    }
    String[] imgs = value.split(StrUtil.COMMA);
    StringBuilder sb = new StringBuilder();
    for (String img : imgs) {
        sb.append(qiniu.getResourcesUrl()).append(img).append(StrUtil.COMMA);
    }
    sb.deleteCharAt(sb.length()-1);
    gen.writeString(sb.toString());
}
 
Example #27
Source File: CustomSerializerTest.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
public CustomSerializer() {
  addSerializer(Custom.class, new JsonSerializer<Custom>() {

    @Override
    public void serialize(Custom custom, JsonGenerator jgen, SerializerProvider provider) throws IOException {
      jgen.writeNumber(custom.getValue());
    }
  });
}
 
Example #28
Source File: GPlusUserActivityCollector.java    From streams with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(
    com.google.api.client.util.DateTime dateTime,
    JsonGenerator jsonGenerator,
    SerializerProvider serializerProvider)
    throws IOException {
  jsonGenerator.writeString(dateTime.toStringRfc3339());
}
 
Example #29
Source File: GroupInfo.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void serialize(final Set<SignalServiceAddress> value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException {
    jgen.writeStartArray(value.size());
    for (SignalServiceAddress address : value) {
        if (address.getUuid().isPresent()) {
            jgen.writeObject(new JsonSignalServiceAddress(address));
        } else {
            jgen.writeString(address.getNumber().get());
        }
    }
    jgen.writeEndArray();
}
 
Example #30
Source File: ReplicaLocation.java    From pegasus with Apache License 2.0 5 votes vote down vote up
/**
 * Serializes contents into YAML representation Sample representation below
 *
 * <pre>
 * lfn: "f2"
 * pfns:
 *   -
 *     pfn: "file:///path/to/file"
 *     site: "local"
 *   -
 *     pfn: "file:///path/to/file"
 *     site: "condorpool"
 * checksum:
 *   sha256: "991232132abc"
 * metadata:
 *   owner: "pegasus"
 *   abc: "123"
 *   size: "1024"
 *   k: "v"
 * </pre>
 *
 * @param r;
 * @param gen
 * @param sp
 * @throws IOException
 */
public void serialize(ReplicaLocation rl, JsonGenerator gen, SerializerProvider sp)
        throws IOException {
    gen.writeStartObject();
    writeStringField(gen, ReplicaCatalogKeywords.LFN.getReservedName(), rl.getLFN());
    if (rl.isRegex()) {
        writeStringField(gen, ReplicaCatalogKeywords.REGEX.getReservedName(), "true");
    }
    if (rl.getPFNCount() > 0) {
        gen.writeArrayFieldStart(ReplicaCatalogKeywords.PFNS.getReservedName());
        for (ReplicaCatalogEntry rce : rl.getPFNList()) {
            gen.writeStartObject();
            // we don't quote or escape anything as serializer
            // always adds enclosing quotes
            writeStringField(
                    gen, ReplicaCatalogKeywords.PFN.getReservedName(), rce.getPFN());
            writeStringField(
                    gen,
                    ReplicaCatalogKeywords.SITE.getReservedName(),
                    rce.getResourceHandle());
            gen.writeEndObject();
        }
        gen.writeEndArray();
    }
    Metadata m = rl.getAllMetadata();
    if (m != null && !m.isEmpty()) {
        gen.writeObject(m);
    }

    gen.writeEndObject();
}