我使用Fastjson将节点对象Node生成JSON字符串时少个对象属性,麻烦你看一下是怎么回事,是bug吗?我用Gson就没出现问题!
这是节点对象文件Node.java
- package per.eblink.pojo;
- public class Node {
- private String id;
- private String pId;
- private String name;
- private boolean open;
- private Node() {
- super();
- }
- public Node(String id,String pId,String name,boolean open) {
- super();
- this.id = id;
- this.pId = pId;
- this.name = name;
- this.open = open;
- }
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public String getpId() {
- return pId;
- }
- public void setpId(String pId) {
- this.pId = pId;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public boolean isOpen() {
- return open;
- }
- public void setOpen(boolean open) {
- this.open = open;
- }
- }
- package per.eblink.test;
-
- import com.alibaba.fastjson.JSON;
- import com.google.gson.Gson;
- import per.eblink.pojo.Node;
-
- public class JsonTest {
-
- /**
- * @param args
- */
- public static void main(String[] args) {
- Node node=new Node("2","1","节点1",true);
- // FastJson转换方式
- String jsonStr=JSON.toJSONString(node);
- // Gson转换方式
- Gson gson=new Gson();
- String gsonStr=gson.toJson(node);
- System.out.println("FastJson生成字符串是:"+jsonStr);
- System.out.println("Gson生成字符串是:"+gsonStr);
- }
- }
最后是控制台打印生成的结果如下:
FastJson生成字符串是:{"id":"2","name":"节点1","open":true}
Gson生成字符串是:{"id":"2","pId":"1","open":true}
用FastJson就是少了个属性pId没有被转化出来,用Gson和其他的却可以,而我的Node对象只是个普通的JAVA类而已,麻烦你看一下,谢谢!
答案:1)你的get,set方法估计多半是自动生成的,Fastjson在生成的时候去判断pId有没有对应的get方法是区分了大小写的,所以找不到对应的get方法(getPId())。
2)如果页面上也需要使用node对象,就必须使用自动生成的get、set方法。与1)相互冲突,最根本的解决办法是,不适用第一个单词只有一个小写字母的属性名,换一个属性名字paId。
问题2:fastjson生成json时Null属性不显示
- Map<String,Object>jsonMap=newHashMap<String,Object>();
- jsonMap.put("a",1);
- "b","");
- "c",null);
- "d",255); background-color:inherit">"wuzhuti.cn");
- Stringstr=JSONObject.toJSONString(jsonMap);
- System.out.println(str);
- //输出结果:{"a":1,"b":"",d:"wuzhuti.cn"}
从输出结果可以看出,null对应的key已经被过滤掉;这明显不是我们想要的结果,这时我们就需要用到fastjson的SerializerFeature序列化属性
也就是这个方法:JSONObject.toJSONString(Object object,SerializerFeature... features)
Fastjson的SerializerFeature序列化属性
QuoteFieldNames———-输出key时是否使用双引号,默认为true
WriteMapNullValue——–是否输出值为null的字段,默认为false
WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null
WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null
WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null
WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null