關於內部類的問題

先上代碼java


public class ChildEvent {

   private String childId;

   private Child child;

   public Child getChild() {
      return child;
   }

   public void setChild(Child child) {
      this.child = child;
   }

   public String getChildId() {
      return childId;
   }

   public void setChildId(String childId) {
      this.childId = childId;
   }

   public static class Child implements Serializable {
      private String cChildId;

      public String getcChildId() {
         return cChildId;
      }

      public void setcChildId(String cChildId) {
         this.cChildId = cChildId;
      }
   }

}複製代碼
@org.junit.Test public void testObj2Str1(){
    //高級set的方式
   ChildEvent childEvent = new ChildEvent() {{
      setChildId("1");
      setChild(new Child() {{
         setcChildId("2");
      }});
   }};
   System.out.println(com.alibaba.fastjson.JSON.toJSONString(childEvent));//輸出{"child":{},"childId":"1"},不會實例化內部類(不管是否是靜態的),因此內部類set的值沒法轉json
   System.out.println(new Gson().toJson(childEvent));//輸出null

   /** * 輸出 * {"child":{},"childId":"1"} * null */
}

@org.junit.Test public void testObj2Str2(){
    //基礎set的方式
   ChildEvent childEvent2 = new ChildEvent();
   childEvent2.setChildId("21");
   ChildEvent.Child child = new ChildEvent.Child();
   child.setcChildId("22");
   childEvent2.setChild(child);
   System.out.println(com.alibaba.fastjson.JSON.toJSONString(childEvent2));
   System.out.println(new Gson().toJson(childEvent2));

   /** * 輸出 * {"child":{},"childId":"21"} * {"childId":"21","child":{"cChildId":"22"}} */
}複製代碼

問題出在內部類,上面兩種set值的方式仍是有差別的json

先說說第一種testObj2Str1this

        用fastjson轉換的時候,fastjson沒法轉內部類(經實踐,無論是不是靜態內部類,都沒法轉),只能轉ChildEvent這個對象spa

        用Gson轉的時候,啥也不能轉,它對這種方式就是不支持。。。code

再說說第二種testObj2Str2:對象

        用fastjson轉換的時候仍是和第一種同樣,因此它只是對內部類敏感而已。。字符串

        用Gson轉的時候,徹底能夠轉,因此它是對高級set的方式敏感。。。get


@org.junit.Test public void testStr2Obj(){
   String childStr = "{\"childId\":\"21\",\"child\":{\"cChildId\":\"22\"}}";
   ChildEvent childEvent = JSON.parseObject(childStr, ChildEvent.class);
   System.out.println(childEvent.getChildId());//21
   System.out.println(childEvent.getChild().getcChildId());//null
}

@org.junit.Test public void testStr2Obj2(){
   String childStr = "{\"childId\":\"21\",\"child\":{\"cChildId\":\"22\"}}";
   ChildEvent childEvent = new Gson().fromJson(childStr, ChildEvent.class);
   System.out.println(childEvent.getChildId());//21
   System.out.println(childEvent.getChild().getcChildId());//22
}複製代碼

一樣的,反過來,字符串轉對象的話,若是用fastjson轉,內部類的值沒法轉string

若是用Gson則能夠正確輸出。不管內部類靜態與否,以上輸出記過不變it

相關文章
相關標籤/搜索