1 package com.fasterxml.jackson.databind.contextual; 2 3 import java.io.IOException; 4 import java.lang.annotation.ElementType; 5 import java.lang.annotation.Retention; 6 import java.lang.annotation.RetentionPolicy; 7 import java.lang.annotation.Target; 8 9 import com.fasterxml.jackson.annotation.JacksonAnnotation; 10 import com.fasterxml.jackson.core.JsonParser; 11 import com.fasterxml.jackson.databind.*; 12 import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 13 import com.fasterxml.jackson.databind.deser.ContextualDeserializer; 14 15 public class TestContextualWithAnnDeserializer extends BaseMapTest 16 { 17 @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE}) 18 @Retention(RetentionPolicy.RUNTIME) 19 @JacksonAnnotation 20 public @interface Name { value()21 public String value(); 22 } 23 24 static class StringValue { 25 protected String value; 26 StringValue(String v)27 public StringValue(String v) { value = v; } 28 } 29 30 static class AnnotatedContextualClassBean 31 { 32 @Name("xyz") 33 @JsonDeserialize(using=AnnotatedContextualDeserializer.class) 34 public StringValue value; 35 } 36 37 static class AnnotatedContextualDeserializer 38 extends JsonDeserializer<StringValue> 39 implements ContextualDeserializer 40 { 41 protected final String _fieldName; 42 AnnotatedContextualDeserializer()43 public AnnotatedContextualDeserializer() { this(""); } AnnotatedContextualDeserializer(String fieldName)44 public AnnotatedContextualDeserializer(String fieldName) { 45 _fieldName = fieldName; 46 } 47 48 @Override deserialize(JsonParser p, DeserializationContext ctxt)49 public StringValue deserialize(JsonParser p, DeserializationContext ctxt) throws IOException 50 { 51 return new StringValue(""+_fieldName+"="+p.getText()); 52 } 53 54 @Override createContextual(DeserializationContext ctxt, BeanProperty property)55 public JsonDeserializer<?> createContextual(DeserializationContext ctxt, 56 BeanProperty property) 57 throws JsonMappingException 58 { 59 Name ann = property.getAnnotation(Name.class); 60 if (ann == null) { 61 ann = property.getContextAnnotation(Name.class); 62 } 63 String propertyName = (ann == null) ? "UNKNOWN" : ann.value(); 64 return new AnnotatedContextualDeserializer(propertyName); 65 } 66 } 67 68 // ensure that direct associations also work testAnnotatedContextual()69 public void testAnnotatedContextual() throws Exception 70 { 71 ObjectMapper mapper = new ObjectMapper(); 72 AnnotatedContextualClassBean bean = mapper.readValue( 73 "{\"value\":\"a\"}", 74 AnnotatedContextualClassBean.class); 75 assertNotNull(bean); 76 assertEquals("xyz=a", bean.value.value); 77 } 78 } 79