Created
January 18, 2014 05:40
-
-
Save flowersinthesand/8486640 to your computer and use it in GitHub Desktop.
Data type conversion example for Portal for Java 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
public abstract class Handler<T> implements Action<Map<String, Object>> { | |
private final Class<T> desiredType; | |
@SuppressWarnings("unchecked") | |
public Handler() { | |
// Each casting is not safe. Improve if you want to use in production | |
// See org.springframework.core.GenericTypeResolver.resolveTypeArgument | |
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass(); | |
desiredType = (Class<T>) pt.getActualTypeArguments()[0]; | |
} | |
@Override | |
public void on(Map<String, Object> map) { | |
// The convertValue will convert map to JSON and JSON to desired type of object | |
// Reflection lib like Apache Commons BeanUtils may be better in performance | |
handle(new ObjectMapper().convertValue(map, desiredType)); | |
} | |
public abstract void handle(T t); | |
} |
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
socket.on(new Handler<Book>() { | |
@Override | |
public void handle(Book book) { | |
// Your logic here | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment