Open sunxiang0918 opened 6 years 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;
}
}
}
发现 SerializerFeature.WriteClassName这个如果是设置在 某一个对象的某一个属性字段上,在JSON.toJSONString的时候并不起作用, 不知道是设计如此还是用法不对?
假设有两个对象 A B :
那么在序列化的时候会有这样的结果:
我想要的效果,其实就是最后一种,也就是
{"b":{"@type":"com.jcg.B","b":"bbbbb"}}
不知道要如何实现?