Advertisement
Guest User

Untitled

a guest
May 4th, 2015
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. package org.springframework.social.dto.ser;
  2.  
  3. import java.io.IOException;
  4. import java.util.HashMap;
  5. import java.util.Iterator;
  6. import java.util.Map;
  7. import java.util.Map.Entry;
  8.  
  9. import com.fasterxml.jackson.core.JsonParser;
  10. import com.fasterxml.jackson.core.JsonProcessingException;
  11. import com.fasterxml.jackson.databind.DeserializationContext;
  12. import com.fasterxml.jackson.databind.JsonNode;
  13. import com.fasterxml.jackson.databind.ObjectMapper;
  14. import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
  15. import com.fasterxml.jackson.databind.node.ObjectNode;
  16.  
  17. /**
  18. * Deserializes documents without a specific field designated for Polymorphic Type
  19. * identification, when the document contains a field registered to be unique to that type
  20. *
  21. * @author robin
  22. */
  23. public class UniquePropertyPolymorphicDeserializer<T> extends StdDeserializer<T> {
  24.  
  25. private static final long serialVersionUID = 1L;
  26.  
  27. // the registry of unique field names to Class types
  28. private Map<String, Class<? extends T>> registry;
  29.  
  30. public UniquePropertyPolymorphicDeserializer(Class<T> clazz) {
  31. super(clazz);
  32. registry = new HashMap<String, Class<? extends T>>();
  33. }
  34.  
  35. public void register(String uniqueProperty, Class<? extends T> clazz) {
  36. registry.put(uniqueProperty, clazz);
  37. }
  38.  
  39. /* (non-Javadoc)
  40. * @see com.fasterxml.jackson.databind.JsonDeserializer#deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext)
  41. */
  42. @Override
  43. public T deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
  44. Class<? extends T> clazz = null;
  45.  
  46. ObjectMapper mapper = (ObjectMapper) jp.getCodec();
  47. ObjectNode obj = (ObjectNode) mapper.readTree(jp);
  48. Iterator<Entry<String, JsonNode>> elementsIterator = obj.fields();
  49.  
  50. while (elementsIterator.hasNext()) {
  51. Entry<String, JsonNode> element = elementsIterator.next();
  52. String name = element.getKey();
  53. if (registry.containsKey(name)) {
  54. clazz = registry.get(name);
  55. break;
  56. }
  57. }
  58.  
  59. if (clazz == null) {
  60. throw ctxt.mappingException("No registered unique properties found for polymorphic deserialization");
  61. }
  62.  
  63. return mapper.treeToValue(obj, clazz);
  64. }
  65.  
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement