1 package com.fasterxml.jackson.databind; 2 3 import java.io.IOException; 4 import java.util.Collection; 5 6 import com.fasterxml.jackson.core.*; 7 8 import com.fasterxml.jackson.databind.deser.*; 9 import com.fasterxml.jackson.databind.deser.impl.ObjectIdReader; 10 import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; 11 import com.fasterxml.jackson.databind.type.LogicalType; 12 import com.fasterxml.jackson.databind.util.AccessPattern; 13 import com.fasterxml.jackson.databind.util.NameTransformer; 14 15 /** 16 * Abstract class that defines API used by {@link ObjectMapper} (and 17 * other chained {@link JsonDeserializer}s too) to deserialize Objects of 18 * arbitrary types from JSON, using provided {@link JsonParser}. 19 *<p> 20 * Custom deserializers should usually not directly extend this class, 21 * but instead extend {@link com.fasterxml.jackson.databind.deser.std.StdDeserializer} 22 * (or its subtypes like {@link com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer}). 23 *<p> 24 * If deserializer is an aggregate one -- meaning it delegates handling of some 25 * of its contents by using other deserializer(s) -- it typically also needs 26 * to implement {@link com.fasterxml.jackson.databind.deser.ResolvableDeserializer}, 27 * which can locate dependant deserializers. This is important to allow dynamic 28 * overrides of deserializers; separate call interface is needed to separate 29 * resolution of dependant deserializers (which may have cyclic link back 30 * to deserializer itself, directly or indirectly). 31 *<p> 32 * In addition, to support per-property annotations (to configure aspects 33 * of deserialization on per-property basis), deserializers may want 34 * to implement 35 * {@link com.fasterxml.jackson.databind.deser.ContextualDeserializer}, 36 * which allows specialization of deserializers: call to 37 * {@link com.fasterxml.jackson.databind.deser.ContextualDeserializer#createContextual} 38 * is passed information on property, and can create a newly configured 39 * deserializer for handling that particular property. 40 *<p> 41 * If both 42 * {@link com.fasterxml.jackson.databind.deser.ResolvableDeserializer} and 43 * {@link com.fasterxml.jackson.databind.deser.ContextualDeserializer} 44 * are implemented, resolution of deserializers occurs before 45 * contextualization. 46 */ 47 public abstract class JsonDeserializer<T> 48 implements NullValueProvider // since 2.9 49 { 50 /* 51 /********************************************************** 52 /* Main deserialization methods 53 /********************************************************** 54 */ 55 56 /** 57 * Method that can be called to ask implementation to deserialize 58 * JSON content into the value type this serializer handles. 59 * Returned instance is to be constructed by method itself. 60 *<p> 61 * Pre-condition for this method is that the parser points to the 62 * first event that is part of value to deserializer (and which 63 * is never JSON 'null' literal, more on this below): for simple 64 * types it may be the only value; and for structured types the 65 * Object start marker or a FIELD_NAME. 66 * </p> 67 * <p> 68 * The two possible input conditions for structured types result 69 * from polymorphism via fields. In the ordinary case, Jackson 70 * calls this method when it has encountered an OBJECT_START, 71 * and the method implementation must advance to the next token to 72 * see the first field name. If the application configures 73 * polymorphism via a field, then the object looks like the following. 74 * <pre> 75 * { 76 * "@class": "class name", 77 * ... 78 * } 79 * </pre> 80 * Jackson consumes the two tokens (the <tt>@class</tt> field name 81 * and its value) in order to learn the class and select the deserializer. 82 * Thus, the stream is pointing to the FIELD_NAME for the first field 83 * after the @class. Thus, if you want your method to work correctly 84 * both with and without polymorphism, you must begin your method with: 85 * <pre> 86 * if (p.currentToken() == JsonToken.START_OBJECT) { 87 * p.nextToken(); 88 * } 89 * </pre> 90 * This results in the stream pointing to the field name, so that 91 * the two conditions align. 92 * <p> 93 * Post-condition is that the parser will point to the last 94 * event that is part of deserialized value (or in case deserialization 95 * fails, event that was not recognized or usable, which may be 96 * the same event as the one it pointed to upon call). 97 *<p> 98 * Note that this method is never called for JSON null literal, 99 * and thus deserializers need (and should) not check for it. 100 * 101 * @param p Parsed used for reading JSON content 102 * @param ctxt Context that can be used to access information about 103 * this deserialization activity. 104 * 105 * @return Deserialized value 106 */ deserialize(JsonParser p, DeserializationContext ctxt)107 public abstract T deserialize(JsonParser p, DeserializationContext ctxt) 108 throws IOException, JsonProcessingException; 109 110 /** 111 * Alternate deserialization method (compared to the most commonly 112 * used, {@link #deserialize(JsonParser, DeserializationContext)}), 113 * which takes in initialized value instance, to be 114 * configured and/or populated by deserializer. 115 * Method is not necessarily used (or supported) by all types 116 * (it will not work for immutable types, for obvious reasons): 117 * most commonly it is used for Collections and Maps. 118 * It may be used both with "updating readers" (for POJOs) and 119 * when Collections and Maps use "getter as setter". 120 *<p> 121 * Default implementation just throws 122 * {@link UnsupportedOperationException}, to indicate that types 123 * that do not explicitly add support do not necessarily support 124 * update-existing-value operation (esp. immutable types) 125 */ deserialize(JsonParser p, DeserializationContext ctxt, T intoValue)126 public T deserialize(JsonParser p, DeserializationContext ctxt, T intoValue) 127 throws IOException 128 { 129 ctxt.handleBadMerge(this); 130 return deserialize(p, ctxt); 131 } 132 133 /** 134 * Deserialization called when type being deserialized is defined to 135 * contain additional type identifier, to allow for correctly 136 * instantiating correct subtype. This can be due to annotation on 137 * type (or its supertype), or due to global settings without 138 * annotations. 139 *<p> 140 * Default implementation may work for some types, but ideally subclasses 141 * should not rely on current default implementation. 142 * Implementation is mostly provided to avoid compilation errors with older 143 * code. 144 * 145 * @param typeDeserializer Deserializer to use for handling type information 146 */ deserializeWithType(JsonParser p, DeserializationContext ctxt, TypeDeserializer typeDeserializer)147 public Object deserializeWithType(JsonParser p, DeserializationContext ctxt, 148 TypeDeserializer typeDeserializer) 149 throws IOException 150 { 151 // We could try calling 152 return typeDeserializer.deserializeTypedFromAny(p, ctxt); 153 } 154 155 /** 156 * Method similar to {@link #deserializeWithType(JsonParser,DeserializationContext,TypeDeserializer)} 157 * but called when merging value. Considered "bad merge" by default implementation, 158 * but if {@link MapperFeature#IGNORE_MERGE_FOR_UNMERGEABLE} is enabled will simple delegate to 159 * {@link #deserializeWithType(JsonParser, DeserializationContext, TypeDeserializer)}. 160 * 161 * @since 2.10 162 */ deserializeWithType(JsonParser p, DeserializationContext ctxt, TypeDeserializer typeDeserializer, T intoValue)163 public Object deserializeWithType(JsonParser p, DeserializationContext ctxt, 164 TypeDeserializer typeDeserializer, T intoValue) 165 throws IOException 166 { 167 ctxt.handleBadMerge(this); 168 return deserializeWithType(p, ctxt, typeDeserializer); 169 } 170 171 /* 172 /********************************************************** 173 /* Fluent factory methods for constructing decorated versions 174 /********************************************************** 175 */ 176 177 /** 178 * Method that will return deserializer instance that is able 179 * to handle "unwrapped" value instances 180 * If no unwrapped instance can be constructed, will simply 181 * return this object as-is. 182 *<p> 183 * Default implementation just returns 'this' 184 * indicating that no unwrapped variant exists 185 */ unwrappingDeserializer(NameTransformer unwrapper)186 public JsonDeserializer<T> unwrappingDeserializer(NameTransformer unwrapper) { 187 return this; 188 } 189 190 /** 191 * Method that can be called to try to replace deserializer this deserializer 192 * delegates calls to. If not supported (either this deserializer does not 193 * delegate anything; or it does not want any changes), should either 194 * throw {@link UnsupportedOperationException} (if operation does not 195 * make sense or is not allowed); or return this deserializer as is. 196 * 197 * @since 2.1 198 */ replaceDelegatee(JsonDeserializer<?> delegatee)199 public JsonDeserializer<?> replaceDelegatee(JsonDeserializer<?> delegatee) { 200 throw new UnsupportedOperationException(); 201 } 202 203 /* 204 /********************************************************** 205 /* Introspection methods for figuring out configuration/setup 206 /* of this deserializer instance and/or type it handles 207 /********************************************************** 208 */ 209 210 /** 211 * Method for accessing concrete physical type of values this deserializer produces. 212 * Note that this information is not guaranteed to be exact -- it 213 * may be a more generic (super-type) -- but it should not be 214 * incorrect (return a non-related type). 215 *<p> 216 * Default implementation will return null, which means almost same 217 * same as returning <code>Object.class</code> would; that is, that 218 * nothing is known about handled type. 219 * 220 * @return Physical type of values this deserializer produces, if known; 221 * {@code null} if not 222 * 223 * @since 2.3 224 */ handledType()225 public Class<?> handledType() { return null; } 226 227 /** 228 * Method for accessing logical type of values this deserializer produces. 229 * Typically used for further configuring handling of values, for example, 230 * to find which coercions are legal. 231 * 232 * @return Logical type of values this deserializer produces, if known; 233 * {@code null} if not 234 * 235 * @since 2.12 236 */ logicalType()237 public LogicalType logicalType() { return null; } 238 239 /** 240 * Method called to see if deserializer instance is cachable and 241 * usable for other properties of same type (type for which instance 242 * was created). 243 *<p> 244 * Note that cached instances are still resolved on per-property basis, 245 * if instance implements {@link com.fasterxml.jackson.databind.deser.ResolvableDeserializer}: 246 * cached instance is just as the base. This means that in most cases it is safe to 247 * cache instances; however, it only makes sense to cache instances 248 * if instantiation is expensive, or if instances are heavy-weight. 249 *<p> 250 * Default implementation returns false, to indicate that no caching 251 * is done. 252 */ isCachable()253 public boolean isCachable() { return false; } 254 255 /** 256 * Accessor that can be used to determine if this deserializer uses 257 * another deserializer for actual deserialization, by delegating 258 * calls. If so, will return immediate delegate (which itself may 259 * delegate to further deserializers); otherwise will return null. 260 * 261 * @return Deserializer this deserializer delegates calls to, if null; 262 * null otherwise. 263 * 264 * @since 2.1 265 */ getDelegatee()266 public JsonDeserializer<?> getDelegatee() { 267 return null; 268 } 269 270 /** 271 * Method that will 272 * either return null to indicate that type being deserializers 273 * has no concept of properties; or a collection of identifiers 274 * for which <code>toString</code> will give external property 275 * name. 276 * This is only to be used for error reporting and diagnostics 277 * purposes (most commonly, to accompany "unknown property" 278 * exception). 279 * 280 * @since 2.0 281 */ getKnownPropertyNames()282 public Collection<Object> getKnownPropertyNames() { 283 return null; 284 } 285 286 /* 287 /********************************************************** 288 /* Default NullValueProvider implementation 289 /********************************************************** 290 */ 291 292 /** 293 * Method that can be called to determine value to be used for 294 * representing null values (values deserialized when JSON token 295 * is {@link JsonToken#VALUE_NULL}). Usually this is simply 296 * Java null, but for some types (especially primitives) it may be 297 * necessary to use non-null values. 298 *<p> 299 * This method may be called once, or multiple times, depending on what 300 * {@link #getNullAccessPattern()} returns. 301 *<p> 302 * Default implementation simply returns null. 303 * 304 * @since 2.6 Added to replace earlier no-arguments variant 305 */ 306 @Override getNullValue(DeserializationContext ctxt)307 public T getNullValue(DeserializationContext ctxt) throws JsonMappingException { 308 // Change the direction in 2.7 309 return getNullValue(); 310 } 311 312 /** 313 * This method may be called in conjunction with calls to 314 * {@link #getNullValue(DeserializationContext)}, to check whether it needs 315 * to be called just once (static values), or each time empty value is 316 * needed. 317 *<p> 318 * Default implementation indicates that "null value" to use for input null 319 * is simply Java `null` for all deserializers, unless overridden by sub-classes. 320 * This information may be used as optimization. 321 */ 322 @Override getNullAccessPattern()323 public AccessPattern getNullAccessPattern() { 324 // Default implementation assumes that the null value does not vary, which 325 // is usually the case for most implementations. But it is not necessarily 326 // `null`; so sub-classes may want to refine further. 327 return AccessPattern.CONSTANT; 328 } 329 330 /** 331 * This method may be called in conjunction with calls to 332 * {@link #getEmptyValue(DeserializationContext)}, to check whether it needs 333 * to be called just once (static values), or each time empty value is 334 * needed. 335 * 336 * @since 2.9 337 */ getEmptyAccessPattern()338 public AccessPattern getEmptyAccessPattern() { 339 return AccessPattern.DYNAMIC; 340 } 341 342 /* 343 /********************************************************** 344 /* Other accessors 345 /********************************************************** 346 */ 347 348 /** 349 * Method called to determine value to be used for "empty" values 350 * (most commonly when deserializing from empty JSON Strings). 351 * Usually this is same as {@link #getNullValue} (which in turn 352 * is usually simply Java null), but it can be overridden 353 * for specific types. Or, if type should never be converted from empty 354 * String, method can also throw an exception. 355 *<p> 356 * This method may be called once, or multiple times, depending on what 357 * {@link #getEmptyAccessPattern()} returns. 358 *<p> 359 * Default implementation simply calls {@link #getNullValue} and 360 * returns value. 361 * 362 * @since 2.6 Added to replace earlier no-arguments variant 363 */ getEmptyValue(DeserializationContext ctxt)364 public Object getEmptyValue(DeserializationContext ctxt) throws JsonMappingException { 365 return getNullValue(ctxt); 366 } 367 368 /** 369 * Accessor that can be used to check whether this deserializer 370 * is expecting to possibly get an Object Identifier value instead of full value 371 * serialization, and if so, should be able to resolve it to actual 372 * Object instance to return as deserialized value. 373 *<p> 374 * Default implementation returns null, as support cannot be implemented 375 * generically. Some standard deserializers (most notably 376 * {@link com.fasterxml.jackson.databind.deser.BeanDeserializer}) 377 * do implement this feature, and may return reader instance, depending on exact 378 * configuration of instance (which is based on type, and referring property). 379 * 380 * @return ObjectIdReader used for resolving possible Object Identifier 381 * value, instead of full value serialization, if deserializer can do that; 382 * null if no Object Id is expected. 383 * 384 * @since 2.0 385 */ getObjectIdReader()386 public ObjectIdReader getObjectIdReader() { return null; } 387 388 /** 389 * Method needed by {@link BeanDeserializerFactory} to properly link 390 * managed- and back-reference pairs. 391 * 392 * @since 2.2 (was moved out of <code>BeanDeserializerBase</code>) 393 */ findBackReference(String refName)394 public SettableBeanProperty findBackReference(String refName) 395 { 396 throw new IllegalArgumentException("Cannot handle managed/back reference '"+refName 397 +"': type: value deserializer of type "+getClass().getName()+" does not support them"); 398 } 399 400 /** 401 * Introspection method that may be called to see whether deserializer supports 402 * update of an existing value (aka "merging") or not. Return value should either 403 * be {@link Boolean#FALSE} if update is not supported at all (immutable values); 404 * {@link Boolean#TRUE} if update should usually work (regular POJOs, for example), 405 * or <code>null</code> if this is either not known, or may sometimes work. 406 *<p> 407 * Information gathered is typically used to either prevent merging update for 408 * property (either by skipping, if based on global defaults; or by exception during 409 * deserialization construction if explicit attempt made) if {@link Boolean#FALSE} 410 * returned, or inclusion if {@link Boolean#TRUE} is specified. If "unknown" case 411 * (<code>null</code> returned) behavior is to exclude property if global defaults 412 * used; or to allow if explicit per-type or property merging is defined. 413 *<p> 414 * Default implementation returns <code>null</code> to allow explicit per-type 415 * or per-property attempts. 416 * 417 * @since 2.9 418 */ supportsUpdate(DeserializationConfig config)419 public Boolean supportsUpdate(DeserializationConfig config) { 420 return null; 421 } 422 423 /* 424 /********************************************************** 425 /* Deprecated methods 426 /********************************************************** 427 */ 428 429 /** 430 * @deprecated Since 2.6 Use overloaded variant that takes context argument 431 */ 432 @Deprecated getNullValue()433 public T getNullValue() { return null; } 434 435 /** 436 * @deprecated Since 2.6 Use overloaded variant that takes context argument 437 */ 438 @Deprecated getEmptyValue()439 public Object getEmptyValue() { return getNullValue(); } 440 441 /* 442 /********************************************************** 443 /* Helper classes 444 /********************************************************** 445 */ 446 447 /** 448 * This marker class is only to be used with annotations, to 449 * indicate that <b>no deserializer is configured</b>. 450 *<p> 451 * Specifically, this class is to be used as the marker for 452 * annotation {@link com.fasterxml.jackson.databind.annotation.JsonDeserialize} 453 */ 454 public abstract static class None extends JsonDeserializer<Object> { None()455 private None() { } // not to be instantiated 456 } 457 } 458