1 package com.fasterxml.jackson.databind.deser.std;
2
3 import java.io.IOException;
4
5 import com.fasterxml.jackson.core.*;
6 import com.fasterxml.jackson.databind.*;
7 import com.fasterxml.jackson.databind.annotation.JacksonStdImpl;
8 import com.fasterxml.jackson.databind.jsontype.TypeDeserializer;
9
10 @JacksonStdImpl
11 public class StringDeserializer extends StdScalarDeserializer<String> // non-final since 2.9
12 {
13     private static final long serialVersionUID = 1L;
14
15     /**
16      * @since 2.2
17      */

18     public final static StringDeserializer instance = new StringDeserializer();
19
20     public StringDeserializer() { super(String.class); }
21
22     // since 2.6, slightly faster lookups for this very common type
23     @Override
24     public boolean isCachable() { return true; }
25
26     @Override // since 2.9
27     public Object getEmptyValue(DeserializationContext ctxt) throws JsonMappingException {
28         return "";
29     }
30
31     @Override
32     public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
33     {
34         if (p.hasToken(JsonToken.VALUE_STRING)) {
35             return p.getText();
36         }
37         JsonToken t = p.currentToken();
38         // [databind#381]
39         if (t == JsonToken.START_ARRAY) {
40             return _deserializeFromArray(p, ctxt);
41         }
42         // need to gracefully handle byte[] data, as base64
43         if (t == JsonToken.VALUE_EMBEDDED_OBJECT) {
44             Object ob = p.getEmbeddedObject();
45             if (ob == null) {
46                 return null;
47             }
48             if (ob instanceof byte[]) {
49                 return ctxt.getBase64Variant().encode((byte[]) ob, false);
50             }
51             // otherwise, try conversion using toString()...
52             return ob.toString();
53         }
54         // allow coercions for other scalar types
55         // 17-Jan-2018, tatu: Related to [databind#1853] avoid FIELD_NAME by ensuring it's
56         //   "real" scalar
57         if (t.isScalarValue()) {
58             String text = p.getValueAsString();
59             if (text != null) {
60                 return text;
61             }
62         }
63         return (String) ctxt.handleUnexpectedToken(_valueClass, p);
64     }
65
66     // Since we can never have type info ("natural type"; String, Boolean, Integer, Double):
67     // (is it an error to even call this version?)
68     @Override
69     public String deserializeWithType(JsonParser p, DeserializationContext ctxt,
70             TypeDeserializer typeDeserializer) throws IOException {
71         return deserialize(p, ctxt);
72     }
73 }
74