Json反序列化之ObjectMapper(⾃定义实现反序列化⽅法)本⽂是在学习中的总结,欢迎转载但请注明出处:
对于服务器端开发⼈员⽽⾔,调⽤第三⽅接⼝获取数据,将其“代理”转化并返给客户端⼏乎是家常便饭的事⼉。⼀般情况下,第三⽅接⼝返回的数据类型是json格式,⽽服务器开发⼈员则需将json格式的数据转换成对象,继⽽对其进⾏处理并封装,以返回给客户端。
在不是特别考虑效率的情况下(对于搜索、缓存等情形可以考虑使⽤thrift和protobuffer),通常我们会选取jackson包中的ObjectMapper类对json串反序列化以得到相应对象。通常会选取readValue(String content, Class<T>valueType)⽅法进⾏反序列化。
ObjectMapper的readValue⽅法将json串反序列化为对象的过程⼤致为:依据传⼊的json串和⽬标对象类型分别创建JsonParse和JavaType,随后⽣成DeserializationConfig、DeserializationContext、JsonDeserializer,其中JsonDeserializer 的实现类决定将要执⾏哪⼀种类型解析(Bean、Map、String等),JsonParse中存储了待解析字符串及其它信息,在解析的过程中通过token来判断当前匹配的类型(例如:如果遇到{,将其判断为对象类型的起始位置;遇到[,将其判断为集合类型的起始位置),⼀旦确定了类型,则跳⼊与之对应的反序列化类中进⾏处理,得到结果,然后token往后移动,接着解析下⼀个串。可以看做类似递归的⽅式进⾏解析,当通过token判断为⼀个对象时,则会跳⼊BeanDeserializer
中进⾏解析,随后遍历该对象的所有字段,如果字段是字符串,则跳到StringDeserializer中进⾏解析,如果字段是数组,则跳到CollectionDeserializer中进⾏解析,直到解析完整个字符串为⽌。也可以看做类似⽽树的深度遍历,理解起来还是挺容易的。
下⾯将简单介绍ObjectMapper的readValue⽅法进⾏反序列化的过程:
a:通过json串和对象类型得到JsonParser和JavaType。
public <T> T readValue(String content, Class<T> valueType)
throws IOException, JsonParseException, JsonMappingException
{
return (T) _readMapAndClose(_ateParser(content), _structType(valueType));
}
//获取json解析器,其中包含带解析的串
public JsonParser createParser(String content) throws IOException, JsonParseException {
final int strLen = content.length();
// Actually, let's use this for medium-sized content, up to 64kB chunk (32kb char)
if (_inputDecorator != null || strLen > 0x8000 || !canUseCharArrays()) {
// easier to just wrap in a Reader than extend InputDecorator; or, if content
// is too long for us to copy it over
return createParser(new StringReader(content));
}
IOContext ctxt = _createContext(content, true);
char[] buf = ctxt.allocTokenBuffer(strLen);
return _createParser(buf, 0, strLen, ctxt, true);
}
//将待解析的类型转化为JavaType类型
public JavaType constructType(Type type) {
return _constructType(type, null);
}
protected JavaType _constructType(Type type, TypeBindings context)
{
JavaType resultType;
// simple class?
if (type instanceof Class<?>) {
resultType = _fromClass((Class<?>) type, context);
}
// But if not, need to start resolving.
json转换对象
else if (type instanceof ParameterizedType) {
resultType = _fromParamType((ParameterizedType) type, context);
}
else if (type instanceof JavaType) { // [Issue#116]
return (JavaType) type;
}
else if (type instanceof GenericArrayType) {
resultType = _fromArrayType((GenericArrayType) type, context);
}
else if (type instanceof TypeVariable<?>) {
resultType = _fromVariable((TypeVariable<?>) type, context);
}
else if (type instanceof WildcardType) {
resultType = _fromWildcard((WildcardType) type, context);
} else {
// sanity check
throw new IllegalArgumentException("Unrecognized Type: "+((type == null) ? "[null]" : String()));        }
if (_modifiers != null && !resultType.isContainerType()) {
for (TypeModifier mod : _modifiers) {
resultType = difyType(resultType, type, context, this);
}
}
return resultType;
}
b、获取反序列化配置对象和上下⽂对象,进⾏第⼀步的序列化操作。
protected Object _readMapAndClose(JsonParser jp, JavaType valueType)
throws IOException, JsonParseException, JsonMappingException
{
try {
Object result;
.
.....
DeserializationConfig cfg = getDeserializationConfig();
DeserializationContext ctxt = createDeserializationContext(jp, cfg);
//依据valueType得到反序列化的解析器
// 对象对应的是beanDeserializer  map对应的是MapDeserializer 。。。。                JsonDeserializer<Object> deser = _findRootDeserializer(ctxt, valueType);                if (cfg.useRootWrapping()) {
result = _unwrapAndDeserialize(jp, ctxt, cfg, valueType, deser);
} else {
//如果是对象,则调到BeanDeserializer类中进⾏解析
result = deser.deserialize(jp, ctxt);
}
ctxt.checkUnresolvedObjectId();
}
// Need to consume the token too
jp.clearCurrentToken();
return result;
} finally {
try {
jp.close();
} catch (IOException ioe) { }
}
}
c、跳⼊到BeanDeserializer类中。
下⾯以BeanDeserializer为例进⾏讲解:
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException
{
JsonToken t = p.getCurrentToken();
// common case first
if (t == JsonToken.START_OBJECT) { // TODO: in 2.6, use 'p.hasTokenId()'            if (_vanillaProcessing) {
return vanillaDeserialize(p, ctxt, p.nextToken());
}
if (_objectIdReader != null) {
return deserializeWithObjectId(p, ctxt);
}
return deserializeFromObject(p, ctxt);
}
return _deserializeOther(p, ctxt, t);
}
/**
* Streamlined version that is only used when no "special"
* features are enabled.
*/
private final Object vanillaDeserialize(JsonParser p,
DeserializationContext ctxt, JsonToken t)
throws IOException
{
final Object bean = _ateUsingDefault(ctxt);
// [databind#631]: Assign current value, to be accessible by custom serializers        p.setCurrentValue(bean);
for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {
String propName = p.getCurrentName();
if (!_beanProperties.findDeserializeAndSet(p, ctxt, bean, propName)) {
handleUnknownVanilla(p, ctxt, bean, propName);
}
}
return bean;
}
/**
* Convenience method that tries to find property with given name, and
* if it is found, call {@link SettableBeanProperty#deserializeAndSet}
* on it, and return true; or, if not found, return false.
* Note, too, that if deserialization is attempted, possible exceptions
* are wrapped if and as necessary, so caller need not handle those.
*
* @since 2.5
*/
public boolean findDeserializeAndSet(JsonParser p, DeserializationContext ctxt,            Object bean, String key) throws IOException
{
if (_caseInsensitive) {
key = LowerCase();
}
int index = key.hashCode() & _hashMask;
Bucket bucket = _buckets[index];
// Let's unroll first lookup since that is null or match in 90+% cases
if (bucket == null) {
return false;
}
// Primarily we do just identity comparison as keys should be interned
if (bucket.key == key) {
try {
bucket.value.deserializeAndSet(p, ctxt, bean);
} catch (Exception e) {
wrapAndThrow(e, bean, key, ctxt);
}
return true;
}
return _findDeserializeAndSet2(p, ctxt, bean, key, index);
}
MethodProperty
@Override
public void deserializeAndSet(JsonParser jp, DeserializationContext ctxt,
Object instance) throws IOException
{
Object value = deserialize(jp, ctxt);
try {
//将得到的结果放⼊反序列化对应的对象中
_setter.invoke(instance, value);
} catch (Exception e) {
_throwAsIOE(e, value);
}
}
public final Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
JsonToken t = p.getCurrentToken();
if (t == JsonToken.VALUE_NULL) {
return (_nullProvider == null) ? null : _nullProvider.nullValue(ctxt);
}
if (_valueTypeDeserializer != null) {
return _valueDeserializer.deserializeWithType(p, ctxt, _valueTypeDeserializer);
}
return _valueDeserializer.deserialize(p, ctxt);
}
//如果继承了JsonDeserializer类重写了deseriakize⽅法,则会跳转到对应注⼊的类中进⾏处理
//不出意外的话最后都会调⽤ DeserializationContext的readValue(JsonParser p, Class<T> type)⽅法,然后会根据type的类型跳转到对应的反序列化类中进⾏处理。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。