FastJson with putDeserializer leads to StackOverflowError

111 views Asked by At

Deserializing object using FastJson with putDeserializer leads to StackOverflowError. What am I doing wrong?

test.json

{
  "openapi": "3.0.1",
  "info": {
    "title": "Swagger Petstore",
    "version": "1.0.0",
    "description": "This is a sample server Petstore server"
  }
}

Spec.java

@Data
public class Spec {
    private String openapi;
    private Info info;
}

Info.java

@Data
public class Info {
    private String title;
    private String version;
    private String description;
}

InfoDeserializer.java

public class InfoDeserializer implements ObjectDeserializer {
    @Override
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object o) {
        Info info = parser.parseObject(Info.class);
        return (T) info;
    }

    @Override
    public int getFastMatchToken() {
        return 0;
    }
}

FastJsonTest.java

public class FastJsonTest {
    @Test
    public void test() throws IOException {
        // Read json file
        File file = new ClassPathResource("test.json").getFile();
        String json = new String(Files.readAllBytes(file.toPath()));

        // Parse json
        ParserConfig config = new ParserConfig();
        config.putDeserializer(Info.class, new InfoDeserializer());
        // This line leads to StackOverflow
        Spec spec = JSON.parseObject(json, Spec.class, config);

        // Assertion
        assertNotNull(spec);
    }
}

However it works if I move deserializer from ParserConfig into JSONField annotation, but with this approach I am not able to pass custom parameters into deserializer.

Spec.java

@Data
public class Spec {
    private String openapi;
    @JSONField(deserializeUsing = InfoDeserializer.class)
    private Info info;
}

FastJsonTest.java

public class FastJsonTest {
    @Test
    public void test() throws IOException {
        // Read json file
        File file = new ClassPathResource("test.json").getFile();
        String json = new String(Files.readAllBytes(file.toPath()));

        // Parse json
        Spec spec = JSON.parseObject(json, Spec.class);

        // Assertion
        assertNotNull(spec);
    }
}
1

There are 1 answers

0
阿尔曼 On BEST ANSWER

After debugging have realized it is supposed to be used this way

public class InfoDeserializer implements ObjectDeserializer {
    @Override
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object o) {
        // Parse to JSONObject first, then parse to your object
        Info info = JSON.parseObject(parser.parseObject().toJSONString(), type);
        return (T) info;
    }

    @Override
    public int getFastMatchToken() {
        return 0;
    }
}