初步瞭解jackson,簡單的使用jackson的annotation

@JsonAutoDetect (class)

這是作用於類的annotation,主要用於指明該類使用annotation,並且可以自動偵測getter,setter,構造方法,以便生成json對象

@JsonIgnore (method/field):作用於方法或字段,用來表明,當生成json的時候忽略有該annotation的方法或字段

如題,以一個用戶對象爲例子:

Java代碼 複製代碼
  1. @Entity
  2. @Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
  3. @JsonAutoDetect
  4. /**
  5. *在此標記不生成json對象的屬性,這裏我標記了兩個屬性一個hibernateLazyInitializer屬性,爲什麼要標記這個
  6. *屬性參考前面的博文,一個password屬性,出於安全這個當然不能轉換成json對象了,畢竟json是在前臺調用的,
  7. *如果你想轉換的時候忽略某個屬性,可以在後面繼續加上
  8. */
  9. @JsonIgnoreProperties(value={"hibernateLazyInitializer","password"})
  10. publicclassUser
  11. {
  12. privateLongid;
  13. privateStringname;
  14. privateStringpassword;
  15. privateStringemail;
  16. privateDatecreateAt;
  17. @Id
  18. @GeneratedValue(strategy=GenerationType.IDENTITY)
  19. publicLonggetId(){
  20. returnid;
  21. }
  22. publicvoidsetId(Longid){
  23. this.id=id;
  24. }
  25. /**
  26. *轉換日期對象的輸出格式,CustomDateSerializer代碼參考前面的博文
  27. */
  28. @JsonSerialize(using=CustomDateSerializer.class)
  29. publicDategetCreateAt(){
  30. returncreateAt;
  31. }
  32. publicvoidsetCreateAt(DatecreateAt){
  33. this.createAt=createAt;
  34. }
  35. /**
  36. *其他的getter和setter省略
  37. */
  38. }
Java代碼 收藏代碼
  1. @Entity
  2. @Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
  3. @JsonAutoDetect
  4. /**
  5. *在此標記不生成json對象的屬性,這裏我標記了兩個屬性一個hibernateLazyInitializer屬性,爲什麼要標記這個
  6. *屬性參考前面的博文,一個password屬性,出於安全這個當然不能轉換成json對象了,畢竟json是在前臺調用的,
  7. *如果你想轉換的時候忽略某個屬性,可以在後面繼續加上
  8. */
  9. @JsonIgnoreProperties(value={"hibernateLazyInitializer","password"})
  10. publicclassUser
  11. {
  12. privateLongid;
  13. privateStringname;
  14. privateStringpassword;
  15. privateStringemail;
  16. privateDatecreateAt;
  17. @Id
  18. @GeneratedValue(strategy=GenerationType.IDENTITY)
  19. publicLonggetId(){
  20. returnid;
  21. }
  22. publicvoidsetId(Longid){
  23. this.id=id;
  24. }
  25. /**
  26. *轉換日期對象的輸出格式,CustomDateSerializer代碼參考前面的博文
  27. */
  28. @JsonSerialize(using=CustomDateSerializer.class)
  29. publicDategetCreateAt(){
  30. returncreateAt;
  31. }
  32. publicvoidsetCreateAt(DatecreateAt){
  33. this.createAt=createAt;
  34. }
  35. /**
  36. *其他的getter和setter省略
  37. */
  38. }

至於中間的什麼service,dao都大同小異就不記錄了

轉到struts2 看看一個用jackson返回json對象的action是如何寫的

Java代碼 複製代碼
  1. @Namespace("/security/user")
  2. publicclassUserActionextendsActionSupport
  3. {
  4. @Action("list")
  5. publicStringlist()throwsException{
  6. //取得所有的用戶
  7. List<User>list=userService.getAll();
  8. response=ServletActionContext.getResponse();
  9. //jackson
  10. ObjectMappermapper=newObjectMapper();
  11. //把取得的用戶list寫入response
  12. mapper.writeValue(response.getWriter(),list);
  13. returnnull;
  14. }
  15. }
Java代碼 收藏代碼
  1. @Namespace("/security/user")
  2. publicclassUserActionextendsActionSupport
  3. {
  4. @Action("list")
  5. publicStringlist()throwsException{
  6. //取得所有的用戶
  7. List<User>list=userService.getAll();
  8. response=ServletActionContext.getResponse();
  9. //jackson
  10. ObjectMappermapper=newObjectMapper();
  11. //把取得的用戶list寫入response
  12. mapper.writeValue(response.getWriter(),list);
  13. returnnull;
  14. }
  15. }

這樣我們在瀏覽器訪問http://yourdomain/security/user/list就可以返回一個包含所有用戶信息的json數組

hibernate延時加載

因爲jsonplugin用的是java的內審機制.hibernate會給被管理的pojo加入一個hibernateLazyInitializer屬性,jsonplugin會把hibernateLazyInitializer也拿出來操作,並讀取裏面一個不能被反射操作的屬性就產生了這個異常.

不過我用的是jackson來轉json,所以想到了用annotation來排除hibernateLazyInitializer 這個屬性

在你的pojo類聲明加上:

Java代碼 複製代碼
  1. @JsonIgnoreProperties(value={"hibernateLazyInitializer"})

轉換格式設置

近日,使用Jackson轉化JSON對象的時候,顯示的時候,日期始終顯示不正確,輸出的日期是一串數字代表的時間戳,不符合要求,所以想到Jackson應當有方法設置輸出的日期格式。後來一查果然有兩種方式來實現:

1.普通的方式:

默認是轉成timestamps形式的,通過下面方式可以取消timestamps。

Java代碼 複製代碼
  1. objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);
Java代碼 收藏代碼
  1. objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);

這樣將使時間生成使用所謂的use a [ISO-8601]-compliant notation, 輸出類似如下格式的時間: "1970-01-01T00:00:00.000+0000".

當然也可以自定義輸出格式:

Java代碼 複製代碼
  1. objectMapper.getSerializationConfig().setDateFormat(myDateFormat);
Java代碼 收藏代碼
  1. objectMapper.getSerializationConfig().setDateFormat(myDateFormat);
Java代碼 複製代碼
  1. myDateFormat對象爲java.text.DateFormat,具體使用清查javaAPI
Java代碼 收藏代碼
  1. myDateFormat對象爲java.text.DateFormat,具體使用清查javaAPI

2.annotaion的註釋方式:

先定義自己需要的格式,例如:

Java代碼 複製代碼
  1. importjava.io.IOException;
  2. importjava.text.SimpleDateFormat;
  3. importjava.util.Date;
  4. importorg.codehaus.jackson.JsonGenerator;
  5. importorg.codehaus.jackson.JsonProcessingException;
  6. importorg.codehaus.jackson.map.JsonSerializer;
  7. importorg.codehaus.jackson.map.SerializerProvider;
  8. /**
  9. *java日期對象經過Jackson庫轉換成JSON日期格式化自定義類
  10. *@authorgodfox
  11. *@date2010-5-3
  12. */
  13. publicclassCustomDateSerializerextendsJsonSerializer<Date>{
  14. @Override
  15. publicvoidserialize(Datevalue,JsonGeneratorjgen,SerializerProviderprovider)throwsIOException,JsonProcessingException{
  16. SimpleDateFormatformatter=newSimpleDateFormat("yyyy-MM-dd");
  17. StringformattedDate=formatter.format(value);
  18. jgen.writeString(formattedDate);
  19. }
  20. }
Java代碼 收藏代碼
  1. importjava.io.IOException;
  2. importjava.text.SimpleDateFormat;
  3. importjava.util.Date;
  4. importorg.codehaus.jackson.JsonGenerator;
  5. importorg.codehaus.jackson.JsonProcessingException;
  6. importorg.codehaus.jackson.map.JsonSerializer;
  7. importorg.codehaus.jackson.map.SerializerProvider;
  8. /**
  9. *java日期對象經過Jackson庫轉換成JSON日期格式化自定義類
  10. *@authorgodfox
  11. *@date2010-5-3
  12. */
  13. publicclassCustomDateSerializerextendsJsonSerializer<Date>{
  14. @Override
  15. publicvoidserialize(Datevalue,JsonGeneratorjgen,SerializerProviderprovider)throwsIOException,JsonProcessingException{
  16. SimpleDateFormatformatter=newSimpleDateFormat("yyyy-MM-dd");
  17. StringformattedDate=formatter.format(value);
  18. jgen.writeString(formattedDate);
  19. }
  20. }

然後在你的POJO上找到日期的get方法

Java代碼 複製代碼
  1. @JsonSerialize(using=CustomDateSerializer.class)
  2. publicDategetCreateAt(){
  3. returncreateAt;
  4. }
發佈了27 篇原創文章 · 獲贊 2 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章