alibaba / fastjson

FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
https://github.com/alibaba/fastjson2/wiki/fastjson_1_upgrade_cn
Apache License 2.0
25.74k stars 6.5k forks source link

在对象的属性上指定 SerializerFeature.WriteClassName 不起作用 #1719

Open sunxiang0918 opened 6 years ago

sunxiang0918 commented 6 years ago

发现 SerializerFeature.WriteClassName这个如果是设置在 某一个对象的某一个属性字段上,在JSON.toJSONString的时候并不起作用, 不知道是设计如此还是用法不对?

假设有两个对象 A B :

@JSONType(serialzeFeatures = SerializerFeature.WriteClassName)
public class B {
    private String b;

    public B() {
    }

   getter/setter
}

public class A {

   // @JSONField(serialzeFeatures = SerializerFeature.WriteClassName) 加不加这个一样
    private B b;

    public A() {
    }
   getter/setter

}

那么在序列化的时候会有这样的结果:


@Test
public void testCase1(){
   B b = new B("bbbbb");
        A a = new A(b);

        System.out.println(JSONUtil.toJSONString(a));     // {"b":{"b":"bbbbb"}}
        System.out.println();
        System.out.println(JSONUtil.toJSONString(b));   // {"@type":"com.jcg.B","b":"bbbbb"}
        System.out.println();
        System.out.println(JSON.toJSONString(a, SerializerFeature.WriteClassName)); // {"@type":"com.jcg.A","b":{"b":"bbbbb"}}
        System.out.println();
        Map<String,Object> c = new HashMap<>();
        c.put("b",b);
        System.out.println(JSONUtil.toJSONString(c)); //{"b":{"@type":"com.jcg.B","b":"bbbbb"}}
}

我想要的效果,其实就是最后一种,也就是{"b":{"@type":"com.jcg.B","b":"bbbbb"}}

不知道要如何实现?

ljluestc commented 4 months ago

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class Main {

    public static void main(String[] args) {
        B b = new B("bbbbb");
        A a = new A(b);

        // 输出 {"b":{"@type":"com.jcg.B","b":"bbbbb"}}
        System.out.println(JSON.toJSONString(a));
    }

    public static class B {
        private String b;

        public B(String b) {
            this.b = b;
        }

        @JSONField(serialize = false) // 设置不写入类名信息
        public String getB() {
            return b;
        }

        public void setB(String b) {
            this.b = b;
        }
    }

    public static class A {
        private B b;

        public A(B b) {
            this.b = b;
        }

        @JSONField(serialzeFeatures = SerializerFeature.WriteClassName) // 在字段上写入类名信息
        public B getB() {
            return b;
        }

        public void setB(B b) {
            this.b = b;
        }
    }
}