Skip to content
This repository has been archived by the owner on Oct 23, 2024. It is now read-only.

fastjson_safemode_en

温绍锦 edited this page Jun 30, 2022 · 2 revisions

Enable SafeMode

since 1.2.68, fastjson support SafeMode, if safeMode enabled, disable autoType completely.

There are three ways to configure safe mode, as follows:

1. Configure in code

ParserConfig.getGlobalInstance().setSafeMode(true); 

2. Configure JVM Options

-Dfastjson.parser.safeMode=true 

If there are multiple package name prefixes, separate them with commas

3. Configure through the fastjson.properties file

Configured through the fastjson.properties file of the classpath, the configuration is as follows:

fastjson.parser.safeMode=true

4. How to do autoType in safeMode scenarios

since version 1.2.68, the AutoTypeCheckHandler extension is provided, and a custom class can take over autoType and register it through the ParserConfig#addAutoTypeCheckHandler method.

	// com.alibaba.fastjson.parser.ParserConfig.AutoTypeCheckHandler
    /**
     * @since 1.2.68
     */
    public interface AutoTypeCheckHandler {
        Class<?> handler(String typeName, Class<?> expectClass, int features);
    }

    // com.alibaba.fastjson.parser.ParserConfig#addAutoTypeCheckHandler

5. How to check if autoType is used

Check if SerializerFeature.WriteClassName is used in the code

JSON.toJSONString(obj, SerializerFeature.WriteClassName); // This scenario would produce @type

6. Use JSONType.autoTypeCheckHandler

since version 1.2.71, a method is provided to configure autoTypeCheckHandler through JSONType, such as:

public class JSONTypeAutoTypeCheckHandlerTest extends TestCase {
    public void test_for_checkAutoType() throws Exception {
        Cat cat = (Cat) JSON.parseObject("{\"@type\":\"Cat\",\"catId\":123}", Animal.class);
        assertEquals(123, cat.catId);
    }

    @JSONType(autoTypeCheckHandler = MyAutoTypeCheckHandler.class)
    public static class Animal {

    }

    public static class Cat extends Animal {
        public int catId;
    }

    public static class Mouse extends Animal {

    }

    public static class MyAutoTypeCheckHandler implements ParserConfig.AutoTypeCheckHandler {

        public Class<?> handler(String typeName, Class<?> expectClass, int features) {
            if ("Cat".equals(typeName)) {
                return Cat.class;
            }

            if ("Mouse".equals(typeName)) {
                return Mouse.class;
            }

            return null;
        }
    }
}
Clone this wiki locally