Is there a way to use Java 8 lambda style to add custom Jackson serializer? - jackson

Right now adding Jackson custom serializer via Jackson module is verbose and does not lend itself to the new Java 8 lambda pattern.
Is there a way to use Java 8 lambda style to add custom Jackson serializer?

You can make a simple Jackson8Module that would allow you to do the following:
ObjectMapper jacksonMapper = new ObjectMapper();
Jackson8Module module = new Jackson8Module();
module.addStringSerializer(LocalDate.class, (val) -> val.toString());
module.addStringSerializer(LocalDateTime.class, (val) -> val.toString());
jacksonMapper.registerModule(module);
The Jackson8Module code just extends Jackson SimpleModule to provide Java 8 friendly methods (it can be extended to support other Jackson Module methods) :
public class Jackson8Module extends SimpleModule {
public <T> void addCustomSerializer(Class<T> cls, SerializeFunction<T> serializeFunction){
JsonSerializer<T> jsonSerializer = new JsonSerializer<T>() {
#Override
public void serialize(T t, JsonGenerator jgen, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
serializeFunction.serialize(t, jgen);
}
};
addSerializer(cls,jsonSerializer);
}
public <T> void addStringSerializer(Class<T> cls, Function<T,String> serializeFunction) {
JsonSerializer<T> jsonSerializer = new JsonSerializer<T>() {
#Override
public void serialize(T t, JsonGenerator jgen, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
String val = serializeFunction.apply(t);
jgen.writeString(val);
}
};
addSerializer(cls,jsonSerializer);
}
public static interface SerializeFunction<T> {
public void serialize(T t, JsonGenerator jgen) throws IOException, JsonProcessingException;
}
}
Here is the gist of the Jackson8Module: https://gist.github.com/jeremychone/a7e06b8baffef88a8816

Related

How to add a simple tab in Intellij Idea plugin

I am creating a simple class diagram plugin for Intellij Idea. I'm struggling now with creating a simple tab in IDE. This tab I will fill up with a prepared JPanel and nothing else.
I have already done the same in NetBeans and I would like to find something with similar behavior as TopComponent in NetBeans provides, but anything working would be cool.
So here is the answer:
create implementation of com.intellij.openapi.fileEditor.FileEditor. This is your actual tab
create implementation of com.intellij.openapi.fileEditor.FileEditorProvider
accept() defines type of files which your editor opens
create() should returns the proper instance of your editor
register your FileEditoProvider in plugin.xml
Editor:
public class YourEditor implements FileEditor {
private VirtualFile file;
public YourEditor(VirtualFile file) {
this.file = file;
}
#Override
public #NotNull JComponent getComponent() {
JPanel tabContent = new JPanel();
tabContent.add(new JButton("foo"));
return tabContent;
}
#Override
public #Nullable JComponent getPreferredFocusedComponent() {
return null;
}
#Override
public #Nls(capitalization = Nls.Capitalization.Title)
#NotNull String getName() {
return "name";
}
#Override
public void setState(#NotNull FileEditorState fileEditorState) {
}
#Override
public boolean isModified() {
return false;
}
#Override
public boolean isValid() {
return true;
}
#Override
public void addPropertyChangeListener(#NotNull PropertyChangeListener propertyChangeListener) {
}
#Override
public void removePropertyChangeListener(#NotNull PropertyChangeListener propertyChangeListener) {
}
#Override
public #Nullable FileEditorLocation getCurrentLocation() {
return null;
}
#Override
public void dispose() {
Disposer.dispose(this);
}
#Override
public <T> #Nullable T getUserData(#NotNull Key<T> key) {
return null;
}
#Override
public <T> void putUserData(#NotNull Key<T> key, #Nullable T t) {
}
#Override
public #Nullable VirtualFile getFile() {
return this.file;
}
}
Provider:
public class YourEditorProvider implements FileEditorProvider, DumbAware {
private static String EDITOR_TYPE_ID = "DiagramView";
#Override
public boolean accept(#NotNull Project project, #NotNull VirtualFile virtualFile) {
return true; //will accept all kind of files, must be specified
}
#Override
public #NotNull
FileEditor createEditor(#NotNull Project project, #NotNull VirtualFile virtualFile) {
return new YourEditor(virtualFile);
}
#Override
public #NotNull
#NonNls
String getEditorTypeId() {
return EDITOR_TYPE_ID;
}
#Override
public #NotNull
FileEditorPolicy getPolicy() {
return FileEditorPolicy.HIDE_DEFAULT_EDITOR;
}
}
and finally put FileEditorProvider extension in pluxin.xml:
<extensions defaultExtensionNs="com.intellij">
<fileEditorProvider implementation="classDiagramPainter.DiagramViewProvider"/>
</extensions>

Jackson-Serialiser: Ignore Field at Serialisation Time

My situation asks for a bit more complex serialisation. I have a class Available (this is a very simplified snippet):
public class Available<T> {
private T value;
private boolean available;
...
}
So a POJO
class Tmp {
private Available<Integer> myInt = Available.of(123);
private Available<Integer> otherInt = Available.clean();
...
}
would normally result in
{"myInt":{available:true,value:123},"otherInt":{available:false,value:null}}
However, I want a serialiser to render the same POJO like this:
{"myInt":123}
What I have now:
public class AvailableSerializer extends JsonSerializer<Available<?>> {
#Override
public void serialize(Available<?> available, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException, JsonProcessingException {
if (available != null && available.isAvailable()) {
jsonGenerator.writeObject(available.getValue());
}
// MISSING: nothing at all should be rendered here for the field
}
#Override
public Class<Available<?>> handledType() {
#SuppressWarnings({ "unchecked", "rawtypes" })
Class<Available<?>> clazz = (Class) Available.class;
return clazz;
}
}
A test
#Test
public void testSerialize() throws Exception {
SimpleModule module = new SimpleModule().addSerializer(new AvailableSerializer());
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(module);
System.out.println(objectMapper.writeValueAsString(new Tmp()));
}
outputs
{"myInt":123,"otherInt"}
Can anyone tell me how to do the "MISSING"-stuff? Or if I'm doing it all wrong, how do I do it then?
The restriction I have is that I don't want the developers to add #Json...-annotations all the time to fields of type Available. So the Tmp-class above is an example of what a typical using class should look like. If that's possible...
Include.NON_DEFAULT
If we assume that your clean method is implemented in this way:
class Available<T> {
public static final Available<Object> EMPTY = clean();
//....
#SuppressWarnings("unchecked")
static <T> Available<T> clean() {
return (Available<T>) EMPTY;
}
}
You can set serialisation inclusion to JsonInclude.Include.NON_DEFAULT value and it should skip values set to EMPTY (default) values. See below example:
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import java.io.IOException;
public class JsonApp {
public static void main(String[] args) throws Exception {
SimpleModule module = new SimpleModule();
module.addSerializer(new AvailableSerializer());
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(module);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
System.out.println(objectMapper.writeValueAsString(new Tmp()));
}
}
class AvailableSerializer extends JsonSerializer<Available<?>> {
#Override
public void serialize(Available<?> value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException {
jsonGenerator.writeObject(value.getValue());
}
#Override
#SuppressWarnings({"unchecked", "rawtypes"})
public Class<Available<?>> handledType() {
return (Class) Available.class;
}
}
Above code prints:
{"myInt":123}
Custom BeanPropertyWriter
If you do not want to use Include.NON_DEFAULT you can write your custom BeanPropertyWriter and skip all values you want. See below example:
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class JsonApp {
public static void main(String[] args) throws Exception {
SimpleModule module = new SimpleModule();
module.addSerializer(new AvailableSerializer());
module.setSerializerModifier(new BeanSerializerModifier() {
#Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
List<BeanPropertyWriter> writers = new ArrayList<>(beanProperties.size());
for (BeanPropertyWriter writer : beanProperties) {
if (writer.getType().getRawClass() == Available.class) {
writer = new SkipNotAvailableBeanPropertyWriter(writer);
}
writers.add(writer);
}
return writers;
}
});
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(module);
System.out.println(objectMapper.writeValueAsString(new Tmp()));
}
}
class AvailableSerializer extends JsonSerializer<Available<?>> {
#Override
public void serialize(Available<?> value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException {
jsonGenerator.writeObject(value.getValue());
}
#Override
#SuppressWarnings({"unchecked", "rawtypes"})
public Class<Available<?>> handledType() {
return (Class) Available.class;
}
}
class SkipNotAvailableBeanPropertyWriter extends BeanPropertyWriter {
SkipNotAvailableBeanPropertyWriter(BeanPropertyWriter base) {
super(base);
}
#Override
public void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception {
// copier from super.serializeAsField(bean, gen, prov);
final Object value = (_accessorMethod == null) ? _field.get(bean) : _accessorMethod.invoke(bean, (Object[]) null);
if (value == null || value instanceof Available && !((Available) value).isAvailable()) {
return;
}
super.serializeAsField(bean, gen, prov);
}
}
Above code prints:
{"myInt":123}
After Michał Ziober's answer I had to look for something regarding Include.NON_DEFAULT and the default object and ran into this answer explaining Include.NON_EMPTY that Google didn't return in my first research (thanks Google).
So things become easier, it's now:
public class AvailableSerializer extends JsonSerializer<Available<?>> {
#Override
public void serialize(Available<?> available, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException, JsonProcessingException {
jsonGenerator.writeObject(available.getValue());
}
#Override
public Class<Available<?>> handledType() {
#SuppressWarnings({ "unchecked", "rawtypes" })
Class<Available<?>> clazz = (Class) Available.class;
return clazz;
}
#Override
public boolean isEmpty(SerializerProvider provider, Available<?> value) {
return value == null || !value.isAvailable();
}
}
with the test
#Test
public void testSerialize() throws Exception {
SimpleModule module = new SimpleModule().addSerializer(availableSerializer);
objectMapper.registerModule(module);
objectMapper.configOverride(Available.class).setInclude(
// the call comes from JavaDoc of objectMapper.setSerializationInclusion(...)
JsonInclude.Value.construct(JsonInclude.Include.NON_EMPTY, JsonInclude.Include.ALWAYS));
Tmp tmp = new Tmp();
assertThat(objectMapper.writeValueAsString(tmp)).isEqualTo("{\"myInt\":123}");
tmp.otherInt.setValue(123);
assertThat(objectMapper.writeValueAsString(tmp)).isEqualTo("{\"myInt\":123,\"otherInt\":123}");
}
So please, if you upvote my answer please also upvote Michał Ziober's as that's also working with a mildly different approach.

How do you adjust json config in Quarkus?

I am attempting to add a mixin to the Jackson's ObjectMapper in a Quarkus project. I have some code that looks likes this:
#Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper mapper;
public ObjectMapperContextResolver() {
this.mapper = createObjectMapper();
}
#Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
private ObjectMapper createObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(MyModel.class, MyMixin.class);
return mapper;
}
}
This code worked perfectly in a Thorntail project I had. For some reason, Quarkus isn't picking this up, and the object mapper is not affected. Is there something different I have to do with the Quarkus CDI?
Updates
Apparently I was a little confused about the implementation. I should be using the Json-B api. I figured out how to change the configuration for Json-B and posted it below.
Instead of providing an ObjectMapper, you can provide a JsonbConfig so that you can customize serialization/deserialization.
Here is what I ended up using:
#Provider
public class JsonConfig implements ContextResolver<Jsonb> {
#Override
public Jsonb getContext(Class type) {
JsonbConfig config = new JsonbConfig();
config.withPropertyVisibilityStrategy(new IgnoreMethods());
return JsonbBuilder.create(config);
}
}
class IgnoreMethods implements PropertyVisibilityStrategy {
#Override
public boolean isVisible(Field field) {
return true;
}
#Override
public boolean isVisible(Method method) {
return false;
}
}
This allows you to customize your JsonbConfig. Here, mine specifically prevents access of methods for serialization/deserialization. On Quarkus with Panache, this prevents isPersistent from appearing in your JSON output.
In addition to the correct answer of #jsolum, here is a working provider which uses the fasterxml-annotations to check visibility of fields and methods:
#Provider
public class JsonConfig implements ContextResolver<Jsonb> {
#Override
public Jsonb getContext(Class aClass) {
JsonbConfig config = new JsonbConfig();
config.withPropertyVisibilityStrategy(new PropertyVisibilityStrategy() {
#Override
public boolean isVisible(Field field) {
JsonIgnore annotation = field.getAnnotation(JsonIgnore.class);
return annotation == null || !annotation.value();
}
#Override
public boolean isVisible(Method method) {
JsonIgnore annotation = method.getAnnotation(JsonIgnore.class);
return annotation == null || !annotation.value();
}
});
return JsonbBuilder.create(config);
}
}
JsonbConfig in Quarkus can be customized providing an ApplicationScoped instance of JsonbConfigCustomizer (taking #jsolum's answer into account):
#ApplicationScoped
public class JsonbFormattingConfig implements JsonbConfigCustomizer {
#Override
public void customize(JsonbConfig jsonbConfig) {
jsonbConfig.withPropertyVisibilityStrategy(new IgnoreMethods());
}
}
class IgnoreMethods implements PropertyVisibilityStrategy {
#Override
public boolean isVisible(Field field) {
return true;
}
#Override
public boolean isVisible(Method method) {
return false;
}
}
Source: https://quarkus.io/guides/rest-json#json-b

When attaching agent to running process, bytebuddy transformer doesn't seem to take effect

The code of my program to be attached is as below.
public class Foo {
}
public class TestEntry {
public TestEntry() {
}
public static void main(String[] args) throws Exception {
try
{
while(true)
{
System.out.println(new Foo().toString());
Thread.sleep(1000);
}
}
catch(Exception e)
{}
}
}
What I attempt to do is to make Foo.toString() returns 'test' by using the following agent.
public class InjectionAgent {
public InjectionAgent() {
}
public static void agentmain(String args, Instrumentation inst) throws Exception
{
System.out.println("agentmain Args:" + args);
new AgentBuilder.Default()
.type(ElementMatchers.named("Foo"))
.transform(new AgentBuilder.Transformer() {
#Override
public Builder<?> transform(Builder<?> arg0, TypeDescription arg1,
ClassLoader arg2, JavaModule arg3) {
return arg0.method(ElementMatchers.named("toString"))
.intercept(FixedValue.value("test"));
}
}).installOn(inst);
}
public static void premain(String args, Instrumentation inst) throws Exception
{
System.out.println("premain Args:" + args);
new AgentBuilder.Default()
.type(ElementMatchers.named("Foo"))
.transform(new AgentBuilder.Transformer() {
#Override
public Builder<?> transform(Builder<?> arg0, TypeDescription arg1,
ClassLoader arg2, JavaModule arg3) {
return arg0.method(ElementMatchers.named("toString"))
.intercept(FixedValue.value("test"));
}
}).installOn(inst);
}
}
I notice that, it was successful when I using -javaagent way, whereas attach way failed, here is code for attach.
public class Injection {
public Injection() {
}
public static void main(String[] args) throws AttachNotSupportedException, IOException, AgentLoadException, AgentInitializationException, InterruptedException {
VirtualMachine vm = null;
String agentjarpath = args[0];
vm = VirtualMachine.attach(args[1]);
vm.loadAgent(agentjarpath, "This is Args to the Agent.");
vm.detach();
}
}
I tried to add AgentBuilder.Listener.StreamWriting.toSystemOut() to the agent, after attaching, the output of TestEntry shows
[Byte Buddy] DISCOVERY Foo [sun.misc.Launcher$AppClassLoader#33909752, null, loaded=true]
[Byte Buddy] TRANSFORM Foo [sun.misc.Launcher$AppClassLoader#33909752, null, loaded=true]
[Byte Buddy] COMPLETE Foo [sun.misc.Launcher$AppClassLoader#33909752, null, loaded=true]
Foo#7f31245a
Foo#6d6f6e28
Foo#135fbaa4
Foo#45ee12a7
Foo#330bedb4
==================================Update=====================================
I defined a public method 'Bar' in Foo like this
public class Foo {
public String Bar()
{
return "Bar";
}
}
and then I was trying to make Foo.Bar() returns "modified" in the following way:
public static void agentmain(String args, Instrumentation inst) throws Exception
{
System.out.println("agentmain Args:" + args);
premain(args, inst);
new AgentBuilder.Default()
.with(RedefinitionStrategy.RETRANSFORMATION)
.disableClassFormatChanges()
.with(AgentBuilder.Listener.StreamWriting.toSystemOut())
.type(ElementMatchers.named("Foo"))
.transform(new AgentBuilder.Transformer() {
#Override
public Builder<?> transform(Builder<?> arg0, TypeDescription arg1,
ClassLoader arg2, JavaModule arg3) {
return arg0.visit(Advice.to(InjectionTemplate.class).on(ElementMatchers.named("Bar")));
}
})
.installOn(inst);
}
static class InjectionTemplate {
#Advice.OnMethodExit
static void exit(#Advice.Return String self) {
System.out.println(self.toString() + " " + self.getClass().toString());
self = new String("modified");
}
}
but I got this error:
java.lang.IllegalStateException: Cannot write to read-only parameter class java.lang.String at 1
any suggestions?
It does not seem like you are using redefinition for your agent. You can activate it using:
new AgentBuilder.Default()
.with(RedefinitionStrategy.RETRANSFORMATION)
.disableClassFormatChanges();
The last part is required on most JVMs (with the notable exception of the dynamic code evolution VM, a custom build of HotSpot). It tells Byte Buddy to not add fields or methods, what most VMs do not support.
In this case, it is no longer possible to invoke the original implementation of a method what is however not required for your FixedValue. Typically, users of Byte Buddy take advantage of Advice when creating an agent that applies dynamic transformations of classes.

Jackson2 custom deserializer factory

I am porting jackson 1.6 code to jackson 2 and stumbled upon a deprecated code.
What i did in jackson 1.6 is:
CustomDeserializerFactory sf = new CustomDeserializerFactory();
mapper.setDeserializerProvider(new StdDeserializerProvider(sf));
sf.addSpecificMapping(BigDecimal.class, new BigDecimalDeserializer());
t = mapper.readValue(ts, X[].class);
Anyone knows how to do it in jackson 2?
To add a factory--not just a deserializer--don't use SimpleModule. Create your own Module and within it create a Deserializers object that is added to the SetUpContext. The Deserializers object will have access to similar methods that the factory did where you can get extra type information about the deserializer needed.
It will look something like this (note that it doesn't need to be an inner class):
public class MyCustomCollectionModule extends Module {
#Override
public void setupModule(final SetupContext context) {
context.addDeserializers(new MyCustomCollectionDeserializers());
}
private static class MyCustomCollectionDeserializers implements Deserializers {
...
#Override
public JsonDeserializer<?> findCollectionDeserializer(final CollectionType type, final DeserializationConfig config, final BeanDescription beanDesc, final TypeDeserializer elementTypeDeserializer, final JsonDeserializer<?> elementDeserializer) throws JsonMappingException {
if (MyCustomCollection.class.equals(type.getRawClass())) {
return new MyCustomCollectionDeserializer(type);
}
return null;
}
...
}
}
In Jackson 2.0:
Create a Module (usually SimpleModule)
Register custom handlers with it.
Call ObjectMapper.registerModule(module);.
This is available on Jackson 1.x as well (since 1.8 or so).
Here is an example of registering a module (in this case Joda date handling) in Jackson 2.x:
ClientConfig clientConfig = new DefaultClientConfig();
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
JacksonJsonProvider provider = new JacksonJsonProvider();
provider.configure(SerializationFeature.INDENT_OUTPUT, true);
provider.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
provider.setMapper(mapper);
clientConfig.getSingletons().add(provider);
Client client = Client.create(clientConfig);
Exemplifying #StaxMan answer
Basically you need to create a module (SimpleModule), add a deserializer and register this module
final SimpleModule sm = new SimpleModule();
sm.addDeserializer(Date.class, new JsonDeserializer<Date>(){
#Override
public Date deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
try {
System.out.println("from my custom deserializer!!!!!!");
return new SimpleDateFormat("yyyy-MM-dd").parse(p.getValueAsString());
} catch (ParseException e) {
System.err.println("aw, it fails: " + e.getMessage());
throw new IOException(e.getMessage());
}
}
});
final CreationBean bean = JsonUtils.getMapper()
.registerModule(sm)
// .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
.readValue("{\"dateCreation\": \"1995-07-19\"}", CreationBean.class);
Here a fully example
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
/**
* #author elvis
* #version $Revision: $<br/>
* $Id: $
* #since 8/22/16 8:38 PM
*/
public class JackCustomDeserializer {
public static void main(String[] args) throws IOException {
final SimpleModule sm = new SimpleModule();
sm.addDeserializer(Date.class, new JsonDeserializer<Date>(){
#Override
public Date deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
try {
System.out.println("from my custom deserializer!!!!!!");
return new SimpleDateFormat("yyyy-MM-dd").parse(p.getValueAsString());
} catch (ParseException e) {
System.err.println("aw, it fails: " + e.getMessage());
throw new IOException(e.getMessage());
}
}
});
final CreationBean bean = JsonUtils.getMapper()
.registerModule(sm)
// .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
.readValue("{\"dateCreation\": \"1995-07-19\"}", CreationBean.class);
System.out.println("parsed bean: " + bean.dateCreation);
}
static class CreationBean {
public Date dateCreation;
}
}