fastjson2 icon indicating copy to clipboard operation
fastjson2 copied to clipboard

[BUG] JSON.parseObject with malformed json

Open Cooperzzy opened this issue 1 year ago • 1 comments

问题描述

基于 #474,解析malformed的json,fastjson2抛exception 而fastjson默认通过解析。

环境信息

  • OS信息: [MacOS 12.7.4 M1 Pro 16 GB]
  • JDK信息: [Openjdk 17.0.6]
  • 版本信息:[Fastjson 2.0.49]

重现步骤

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.List;

public class Issue474Mutated_203 {
    @Test
    public void test() {
        Item item1 = new Item("item1");
        Item item2 = new Item("item2");
        Result result = new Result(Arrays.asList(item1, item2));
        Response<Result> response = new Response<>(result);
        String json = JSON.toJSONString(response);

        String malform = json + ",malformed";
        System.out.println(malform);
        malformedFastJsonParse(malform, Result.class);
        malformedFastJson2Parse(malform, Result.class);
    }

    static <T extends AbstractResult> T malformedFastJson2Parse(String json, Class<?> clazz) {
        TypeReference<Response<T>> typeReference = new TypeReference<Response<T>>(clazz) {
        };
        Response<T> result = JSON.parseObject(json, typeReference);
        return result.getData();
    }

    static <T extends AbstractResult> T malformedFastJsonParse(String json, Class<?> clazz) {
        com.alibaba.fastjson.TypeReference<Response<T>> typeReference = new com.alibaba.fastjson.TypeReference<Response<T>>(clazz) {
        };
        Response<T> result = com.alibaba.fastjson.JSON.parseObject(json, typeReference);
        return result.getData();
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Response<T extends AbstractResult> {
        private T data;
    }

    public abstract static class AbstractResult {
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Result
            extends AbstractResult {
        List<Item> items;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Item {
        private String name;
    }
}

期待的正确结果

fastjson.JSON.parseObject should throw proper exception when parsing malformed json.

相关日志输出

com.alibaba.fastjson2.JSONException: input not end, offset 56, character m, line 1, column 56, fastjson-version 2.0.49 {"data":{"items":[{"name":"item1"},{"name":"item2"}]}},malformed at com.alibaba.fastjson2.JSON.parseObject(JSON.java:996) at Issue474Mutated_203.malformedFastJson2Parse(Issue474Mutated_203.java:34)

Cooperzzy avatar May 08 '24 07:05 Cooperzzy

fastjson 1.2.83和fastjson2 2.0.50解析会抛异常,但fastjson compatible 2.0.50 能够解析

Cooperzzy avatar May 17 '24 03:05 Cooperzzy

已修复

Cooperzzy avatar Jun 30 '24 13:06 Cooperzzy