fastjson使用注意事项

fastjson git:https://github.com/alibaba/fastjson/
注意事项:
1.属性这么写要注意了

    public String aTest;

    public String getaTest() {
        return aTest;
    }

    public void setaTest(String aTest) {
        this.aTest = aTest;
    }

这种get,set方法是自动生成的,这样会导致反序列化不回来,方法这样就可以getATest setATest
2.注解@JSONField的使用, ,可以写在属性上,也可以写在方法上

定义序列化的key

@JSONField(name="ID")

使用serialize/deserialize指定字段不序列化

@JSONField(serialize=false)
@JSONField(deserialize=false)

一定要注意,如果在序列化的类里写的方法是以get开头的无参的,比如getTest()方法,即使这个类里没有test属性,fastjson还是会序列化到字符串中去,所以这种方法一定要serialize=false
3.反序列化方法的传参问题

例如:
Map<String,Long> map = new ConcurrentHashMap<String,Long>();
String text = JSON.toJSONString(map);
Map<String,Long> map1 = JSON.parseObject(text,new TypeReference<ConcurrentHashMap<String, Long>>() {});

反序列化的时候第二个参数一定要这么写:

new TypeReference<ConcurrentHashMap<String, Long>>() {}

如果写成下面这样会导致一些问题,因为会反序列化成一些默认的实现类,而不是你需要的ConcurrentHashMap

new TypeReference<Map<String, Long>>() {}

4.有个父类子类的问题,比如
Map<String,A> map = new HashMap<String,A>();
实际上put进去一个AA,AA是A的子类,这样反序列化回来的map里会是A,而不是AA,用下面方式解决
String s = JSON.toJSONString(o, SerializerFeature.WriteClassName);
或者调用序列化之前
JSON.DEFAULT_GENERATE_FEATURE |=SerializerFeature.WriteClassName.getMask();

猜你喜欢

转载自watersrc.iteye.com/blog/2345034