Skip to content

[BUG]toJSON转换object中有集合list时报错,在JSON.toJSON(object, JSONWriter.Feature.ReferenceDetection) #3432

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
1277121822 opened this issue Mar 21, 2025 · 0 comments
Labels
bug Something isn't working

Comments

@1277121822
Copy link

1277121822 commented Mar 21, 2025

问题描述

toJSON转换object中有集合list时报错,在JSON.toJSON(object, JSONWriter.Feature.ReferenceDetection)

环境信息

请填写以下信息:

  • OS信息: [e.g.:CentOS 8.4.2105 4Core 3.10GHz 16 GB]
  • JDK信息: [e.g.:Openjdk 1.8.0_312]
  • 版本信息:[e.g.:Fastjson2 2.0.54]

重现步骤

如何操作可以重现该问题:

  1. 使用 JSON.toJSON(nodes, JSONWriter.Feature.ReferenceDetection) 方法
  2. 输入 含有list字段的对象 数据,具体如下nodes
        List<Node> nodes = new ArrayList<>();
        Node node = new Node();
        node.setGradeId("123");
        node.setPrivilegeIds(Arrays.asList("1", "2"));
        nodes.add(node);

3.执行如下代码即可复现```java

public void test_toJSON() {
    List<Node> nodes = new ArrayList<>();
    Node node = new Node();
    node.setGradeId("123");
    node.setPrivilegeIds(Arrays.asList("1", "2"));
    nodes.add(node);

    // 1.x版本
    Object json1 = com.alibaba.fastjson.JSON.toJSON(nodes);
    assertNotNull(json1);
    // 2.x版本 当启用循环检测时,报错
    JSONException jsonException =
        assertThrows(JSONException.class, () -> JSON.toJSON(nodes, JSONWriter.Feature.ReferenceDetection));
    assertNotNull(jsonException);
    log.error("", jsonException);

    Object json2_2 = JSON.toJSON(nodes);
    assertNotNull(json2_2);
}
对象如下 ```java
class Node {

    private String gradeId;

    private List<String> privilegeIds;

}
  1. 出现 错误
com.alibaba.fastjson2.JSONException: toJSONString error
	at com.alibaba.fastjson2.JSON.toJSON(JSON.java:3934) ~[fastjson2-2.0.54.jar:?]
... 
Caused by: java.lang.NullPointerException
	at com.alibaba.fastjson2.JSONWriter.setPath(JSONWriter.java:203) ~[fastjson2-2.0.54.jar:?]
	at com.alibaba.fastjson2.writer.ObjectWriterImplList.write(ObjectWriterImplList.java:362) ~[fastjson2-2.0.54.jar:?]
	at com.alibaba.fastjson2.JSON.toJSON(JSON.java:3931) ~[fastjson2-2.0.54.jar:?]

期待的正确结果

可正常转换为json数据格式

附加信息

如果你还有其他需要提供的信息,可以在这里填写(可以提供截图、视频等)。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant