關於Gson和FastJson的坑

sweetmain發表於2017-12-14

字串轉 POJO

{
  "advNote" : "測試note",
  "lastTime" : 1513131060000,
  "thumb" : "http://127.0.0.1/iHkobK0_7XQxN06gtCIVCFfWjx8",
  "goodsGroupThumb" : "http://127.0.0.1/iHkobK0_7XQxN06gtCIVCFfWjx8",
  "goodsGroup" : [ "馬良" ],
  "sortNo" : 1513130723865,
  "createTime" : 1513130700000,
  "name" : "444個人",
  "id" : "2c91b5ae6034bbd101604d9e8a4dua"
}
複製程式碼

pojo.java

public class GoodsAdv {
  private String id;

  private Date createTime;

  private Date lastTime;

  private String advertisingPosition;

  private Date beginTime;

  private String advertisingType;

  private String vendorType;

  private String thumb;

  private Date endTime;

  private String couponEffectType;

  private String goodsGroup;

  private String name;

  private String advNote;

  private Long sortNo;

  private String auditStatus;

  private String goodsGroupThumb;
    // setter .. getter
}
複製程式碼

使用 Gson 轉 POJO 物件就會報錯,原因就在 goodsGroup 這個欄位, 而 FastJson 沒有問題,可以正常轉換

 public static void main(String[] args) {
    String str = "{\"advNote\":\"測試note\",\"lastTime\":1513131060000,\"thumb\":\"http://qiniu.xuduolove.com/FiHkobK0_7XQxN06gtCIVCFfWjx8\",\"goodsGroupThumb\":\"http://qiniu.xuduolove.com/FiHkobK0_7XQxN06gtCIVCFfWjx8\",\"goodsGroup\":[\"馬良\"],\"sortNo\":1513130723865,\"createTime\":1513130700000,\"name\":\"444個人\",\"id\":\"2c91b5ae6034bbd101604d9e8a1d0068\"}";

    GsonBuilder builder = new GsonBuilder();

    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
      public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return new Date(json.getAsJsonPrimitive().getAsLong());
      }
    });

    Gson gson = builder.create();
    GoodsAdv goodsAdv = gson.fromJson(str, GoodsAdv.class);

    System.out.println(goodsAdv+"\n");

    GoodsAdv goodsAdv1 = JSONObject.parseObject(str, GoodsAdv.class);

    System.out.println(goodsAdv1+"\n");
    
  }
複製程式碼

Gson 版本

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
</dependency>
複製程式碼

相關文章