public <T> T readValue(String content, Class<T> valueType)
throws IOException, JsonParseException, JsonMappingException
{
return (T) _readMapAndClose(_jsonFactory.createParser(content), _typeFactory.constructType(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);
content.getChars(0, strLen, buf, 0);
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.
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]" : type.toString()));
}
if (_modifiers != null && !resultType.isContainerType()) {
for (TypeModifier mod : _modifiers) {
resultType = mod.modifyType(resultType, type, context, this);
}
}
return resultType;
}
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) { }
}
}
下面以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());
}
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 = _valueInstantiator.createUsingDefault(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();
p.nextToken();
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 = key.toLowerCase();
}
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的类型跳转到对应的反序列化类中进行处理。
public <T> T readValue(JsonParser p, Class<T> type) throws IOException {
return readValue(p, getTypeFactory().constructType(type));
}
@SuppressWarnings("unchecked")
public <T> T readValue(JsonParser p, JavaType type) throws IOException {
//得到最终解析的类型,Map list string。。。。
JsonDeserializer<Object> deser = findRootValueDeserializer(type);
if (deser == null) {
}
return (T) deser.deserialize(p, this);
}
//例如这里如果是一个map,则会调用MapDeserializer的deserizlize方法得到最后的返回结果。
//对于集合类,会通过token按照顺序解析生成一个个的集合对象并放入集合中。
JsonToken t;
while ((t = p.nextToken()) != JsonToken.END_ARRAY) {
try {
Object value;
if (t == JsonToken.VALUE_NULL) {
value = valueDes.getNullValue();
} else if (typeDeser == null) {
value = valueDes.deserialize(p, ctxt);
} else {
value = valueDes.deserializeWithType(p, ctxt, typeDeser);
}
if (referringAccumulator != null) {
referringAccumulator.add(value);
} else {
result.add(value);
}
} catch (UnresolvedForwardReference reference) {
if (referringAccumulator == null) {
throw JsonMappingException
.from(p, "Unresolved forward reference but no identity info", reference);
}
Referring ref = referringAccumulator.handleUnresolvedReference(reference);
reference.getRoid().appendReferring(ref);
} catch (Exception e) {
throw JsonMappingException.wrapWithPath(e, result, result.size());
}
}
return result;
package com.string;
import java.util.Map;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
public class Comment {
public String id;
@JsonDeserialize(using = ImgPackSerializer.class)
public Map<String, String> imgPack;
@JsonDeserialize(using = CoopSerializer.class)
public Coop coop;
public Coop getCoop() {
return coop;
}
public void setCoop(Coop coop) {
this.coop = coop;
}
public Map<String, String> getImgPack() {
return imgPack;
}
public void setImgPack(Map<String, String> imgPack) {
this.imgPack = imgPack;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
class Coop {
public Integer age;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
package com.string;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TestJson {
static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public static void main(String[] args) {
String s = "{"code":"1","comm":[{"imgPack":{"abc":"abc"},"coop":[]}],"name":"car"}";
try {
Response readValue = OBJECT_MAPPER.readValue(s, Response.class);
System.err.println(readValue.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Response {
public String code;
public List<Comment> comm;
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public List<Comment> getComm() {
return comm;
}
public void setComm(List<Comment> comm) {
this.comm = comm;
}
}
class CoopSerializer extends JsonDeserializer<Coop> {
@Override
public Coop deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonToken currentToken = jp.getCurrentToken();
if (currentToken == JsonToken.START_ARRAY) {
// return null; //error may create more object
// jp.nextToken(); //error
return ctxt.readValue(jp, Object.class) == null ? null : null;
} else if (currentToken == JsonToken.START_OBJECT) {
return (Coop) ctxt.readValue(jp, Coop.class);
}
return null;
}
}
class ImgPackSerializer extends JsonDeserializer<Map<String, String>> {
@Override
public Map<String, String> deserialize(JsonParser jp,
DeserializationContext ctxt) throws IOException,
JsonProcessingException {
JsonToken currentToken = jp.getCurrentToken();
if (currentToken == JsonToken.START_ARRAY) {
return ctxt.readValue(jp, Object.class) == null ? null : null;
} else if (currentToken == JsonToken.START_OBJECT) {
return (Map<String, String>) ctxt.readValue(jp, Map.class);
}
return null;
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有