de.schegge.bitrate.BitrateModule Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jackson-bitrate-support Show documentation
Show all versions of jackson-bitrate-support Show documentation
Jackson Module for Bitrate Support
The newest version!
package de.schegge.bitrate;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleDeserializers;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.module.SimpleSerializers;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.fasterxml.jackson.databind.type.ReferenceType;
import com.fasterxml.jackson.databind.type.SimpleType;
import com.fasterxml.jackson.databind.util.ClassUtil;
import tech.units.indriya.quantity.Quantities;
import javax.measure.Quantity;
import javax.measure.Unit;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class BitrateModule extends SimpleModule {
private Unit serializerBitrate;
@Override
public void setupModule(SetupContext context) {
context.addSerializers(new SimpleSerializers(List.of(new StdSerializer>(ReferenceType.upgradeFrom(SimpleType.constructUnsafe(Quantity.class), SimpleType.constructUnsafe(Bitrate.class))) {
@Override
public void serialize(Quantity quantity, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
Quantity currentQuantity = serializerBitrate != null ? quantity.to(serializerBitrate) : quantity;
jsonGenerator.writeString(currentQuantity.toString());
}
})));
context.addDeserializers(new SimpleDeserializers(Map.of(Quantity.class, new StdDeserializer>(Quantity.class) {
@Override
@SuppressWarnings("unchecked")
public Quantity deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
try {
return (Quantity) Quantities.getQuantity(jsonParser.getValueAsString());
} catch (IllegalArgumentException e) {
return (Quantity) deserializationContext.handleWeirdStringValue(_valueClass, jsonParser.getValueAsString(),
"not a valid representation (error: %s)", ClassUtil.exceptionMessage(e));
}
}
})));
}
public BitrateModule withSerializerBitrate(Unit serializerBitrate) {
this.serializerBitrate = serializerBitrate;
return this;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy