fastjson2 icon indicating copy to clipboard operation
fastjson2 copied to clipboard

[BUG]JSON.toJSON和JSON.toJSONString对值为null的属性处理逻辑不一致

Open the3rd opened this issue 2 years ago • 2 comments

问题描述

使用默认feature时,JSON.toJSON和JSON.toJSONString对值为null的属性处理逻辑不一致, JSON.toJSON保留了值为null的属性,JSON.toJSONString则忽略了null值属性。

期待的正确结果

JSON.toJSON默认也忽略null值属性,除非显式指明JSONWriter.Feature.WriteNulls。

the3rd avatar Nov 08 '23 03:11 the3rd

能帮忙提供重现问题的testcase么?

wenshao avatar Nov 12 '23 15:11 wenshao

@wenshao

package org.example;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.junit.jupiter.api.Assertions;

class Test {

    public static class A {
        private String a1;
        private String a2;

        public String getA1() {
            return a1;
        }

        public void setA1(String a1) {
            this.a1 = a1;
        }

        public String getA2() {
            return a2;
        }

        public void setA2(String a2) {
            this.a2 = a2;
        }
    }

    @org.junit.jupiter.api.Test
    public void testNullWithToJson() {
        A a = new A();
        a.setA1(null);
        a.setA2("a2");
        JSONObject jo = (JSONObject) JSON.toJSON(a);
        Assertions.assertFalse(jo.containsKey("a1")); // 这里不能通过!
    }

    @org.junit.jupiter.api.Test
    public void testNullWithToJsonString() {
        A a = new A();
        a.setA1(null);
        a.setA2("a2");
        String str = JSON.toJSONString(a);
        Assertions.assertFalse(str.contains("a1"));  // 这里通过了
    }

}

the3rd avatar Nov 13 '23 01:11 the3rd