Created
August 8, 2016 18:00
-
-
Save baconstrudel/8cb9ec854eac941693e4baf7809a438d to your computer and use it in GitHub Desktop.
deserialising subclasses with jackson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main; | |
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; | |
import com.fasterxml.jackson.core.JsonProcessingException; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import java.io.IOException; | |
import java.lang.reflect.InvocationTargetException; | |
import java.lang.reflect.Method; | |
import java.util.Arrays; | |
abstract class Parent { | |
public String getType(){ | |
return this.getClass().getCanonicalName(); | |
} | |
String serialize() throws JsonProcessingException { return new ObjectMapper().writeValueAsString(this);} | |
} | |
@JsonIgnoreProperties(ignoreUnknown = true) | |
class Son extends Parent { | |
static Parent deserialize(String json) throws IOException { | |
return new ObjectMapper().readValue(json, Son.class); | |
} | |
} | |
@JsonIgnoreProperties(ignoreUnknown = true) | |
class Daughter extends Parent { | |
static Parent deserialize(String json) throws IOException { | |
return new ObjectMapper().readValue(json, Daughter.class); | |
} | |
} | |
public class run { | |
public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, NoSuchMethodException, IOException { | |
Parent[] events = new Parent[]{new Daughter(), new Son(), new Daughter(), new Son() }; | |
String[] serialisedEvents = new String[events.length]; | |
for(int i = 0; i < events.length; i++){ | |
serialisedEvents[i] = events[i].serialize(); | |
} | |
Parent[] deserialisedEvents = new Parent[events.length]; | |
for(int i = 0; i < events.length; i++){ | |
String typeName = new ObjectMapper().readTree(serialisedEvents[i]).get("type").textValue(); | |
final Method deserialize = Class.forName(typeName).asSubclass(Parent.class).getDeclaredMethod("deserialize", new Class[]{String.class}); | |
int j = deserialize.getParameterCount(); | |
final Class<?>[] parameterTypes = deserialize.getParameterTypes(); | |
deserialisedEvents[i] = (Parent) deserialize.invoke(null, serialisedEvents[i]); | |
} | |
System.out.printf("events:\n%s%n", Arrays.toString(events)); | |
System.out.printf("serialized events:\n%s%n", Arrays.toString(serialisedEvents)); | |
System.out.printf("deserialized events:\n%s%n", Arrays.toString(deserialisedEvents)); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment