@JsonAutoDetect (class)
這是作用於類的annotation,主要用於指明該類使用annotation,並且可以自動偵測getter,setter,構造方法,以便生成json對象
@JsonIgnore (method/field):作用於方法或字段,用來表明,當生成json的時候忽略有該annotation的方法或字段
如題,以一個用戶對象爲例子:
- @Entity
- @Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
- @JsonAutoDetect
- /**
- *在此標記不生成json對象的屬性,這裏我標記了兩個屬性一個hibernateLazyInitializer屬性,爲什麼要標記這個
- *屬性參考前面的博文,一個password屬性,出於安全這個當然不能轉換成json對象了,畢竟json是在前臺調用的,
- *如果你想轉換的時候忽略某個屬性,可以在後面繼續加上
- */
- @JsonIgnoreProperties(value={"hibernateLazyInitializer","password"})
- publicclassUser
- {
- privateLongid;
- privateStringname;
- privateStringpassword;
- privateStringemail;
- privateDatecreateAt;
- @Id
- @GeneratedValue(strategy=GenerationType.IDENTITY)
- publicLonggetId(){
- returnid;
- }
- publicvoidsetId(Longid){
- this.id=id;
- }
- /**
- *轉換日期對象的輸出格式,CustomDateSerializer代碼參考前面的博文
- */
- @JsonSerialize(using=CustomDateSerializer.class)
- publicDategetCreateAt(){
- returncreateAt;
- }
- publicvoidsetCreateAt(DatecreateAt){
- this.createAt=createAt;
- }
- /**
- *其他的getter和setter省略
- */
- }
- @Entity
- @Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
- @JsonAutoDetect
- /**
- *在此標記不生成json對象的屬性,這裏我標記了兩個屬性一個hibernateLazyInitializer屬性,爲什麼要標記這個
- *屬性參考前面的博文,一個password屬性,出於安全這個當然不能轉換成json對象了,畢竟json是在前臺調用的,
- *如果你想轉換的時候忽略某個屬性,可以在後面繼續加上
- */
- @JsonIgnoreProperties(value={"hibernateLazyInitializer","password"})
- publicclassUser
- {
- privateLongid;
- privateStringname;
- privateStringpassword;
- privateStringemail;
- privateDatecreateAt;
- @Id
- @GeneratedValue(strategy=GenerationType.IDENTITY)
- publicLonggetId(){
- returnid;
- }
- publicvoidsetId(Longid){
- this.id=id;
- }
- /**
- *轉換日期對象的輸出格式,CustomDateSerializer代碼參考前面的博文
- */
- @JsonSerialize(using=CustomDateSerializer.class)
- publicDategetCreateAt(){
- returncreateAt;
- }
- publicvoidsetCreateAt(DatecreateAt){
- this.createAt=createAt;
- }
- /**
- *其他的getter和setter省略
- */
- }
至於中間的什麼service,dao都大同小異就不記錄了
轉到struts2 看看一個用jackson返回json對象的action是如何寫的
- @Namespace("/security/user")
- publicclassUserActionextendsActionSupport
- {
- @Action("list")
- publicStringlist()throwsException{
- //取得所有的用戶
- List<User>list=userService.getAll();
- response=ServletActionContext.getResponse();
- //jackson
- ObjectMappermapper=newObjectMapper();
- //把取得的用戶list寫入response
- mapper.writeValue(response.getWriter(),list);
- returnnull;
- }
- }
- @Namespace("/security/user")
- publicclassUserActionextendsActionSupport
- {
- @Action("list")
- publicStringlist()throwsException{
- //取得所有的用戶
- List<User>list=userService.getAll();
- response=ServletActionContext.getResponse();
- //jackson
- ObjectMappermapper=newObjectMapper();
- //把取得的用戶list寫入response
- mapper.writeValue(response.getWriter(),list);
- returnnull;
- }
- }
這樣我們在瀏覽器訪問http://yourdomain/security/user/list就可以返回一個包含所有用戶信息的json數組
hibernate延時加載
因爲jsonplugin用的是java的內審機制.hibernate會給被管理的pojo加入一個hibernateLazyInitializer屬性,jsonplugin會把hibernateLazyInitializer也拿出來操作,並讀取裏面一個不能被反射操作的屬性就產生了這個異常.
不過我用的是jackson來轉json,所以想到了用annotation來排除hibernateLazyInitializer 這個屬性
在你的pojo類聲明加上:
- @JsonIgnoreProperties(value={"hibernateLazyInitializer"})
轉換格式設置
近日,使用Jackson轉化JSON對象的時候,顯示的時候,日期始終顯示不正確,輸出的日期是一串數字代表的時間戳,不符合要求,所以想到Jackson應當有方法設置輸出的日期格式。後來一查果然有兩種方式來實現:
1.普通的方式:
默認是轉成timestamps形式的,通過下面方式可以取消timestamps。
- objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);
- objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);
這樣將使時間生成使用所謂的use a [ISO-8601]-compliant notation, 輸出類似如下格式的時間: "1970-01-01T00:00:00.000+0000".
當然也可以自定義輸出格式:
- objectMapper.getSerializationConfig().setDateFormat(myDateFormat);
- objectMapper.getSerializationConfig().setDateFormat(myDateFormat);
- myDateFormat對象爲java.text.DateFormat,具體使用清查javaAPI
- myDateFormat對象爲java.text.DateFormat,具體使用清查javaAPI
2.annotaion的註釋方式:
先定義自己需要的格式,例如:
- importjava.io.IOException;
- importjava.text.SimpleDateFormat;
- importjava.util.Date;
- importorg.codehaus.jackson.JsonGenerator;
- importorg.codehaus.jackson.JsonProcessingException;
- importorg.codehaus.jackson.map.JsonSerializer;
- importorg.codehaus.jackson.map.SerializerProvider;
- /**
- *java日期對象經過Jackson庫轉換成JSON日期格式化自定義類
- *@authorgodfox
- *@date2010-5-3
- */
- publicclassCustomDateSerializerextendsJsonSerializer<Date>{
- @Override
- publicvoidserialize(Datevalue,JsonGeneratorjgen,SerializerProviderprovider)throwsIOException,JsonProcessingException{
- SimpleDateFormatformatter=newSimpleDateFormat("yyyy-MM-dd");
- StringformattedDate=formatter.format(value);
- jgen.writeString(formattedDate);
- }
- }
- importjava.io.IOException;
- importjava.text.SimpleDateFormat;
- importjava.util.Date;
- importorg.codehaus.jackson.JsonGenerator;
- importorg.codehaus.jackson.JsonProcessingException;
- importorg.codehaus.jackson.map.JsonSerializer;
- importorg.codehaus.jackson.map.SerializerProvider;
- /**
- *java日期對象經過Jackson庫轉換成JSON日期格式化自定義類
- *@authorgodfox
- *@date2010-5-3
- */
- publicclassCustomDateSerializerextendsJsonSerializer<Date>{
- @Override
- publicvoidserialize(Datevalue,JsonGeneratorjgen,SerializerProviderprovider)throwsIOException,JsonProcessingException{
- SimpleDateFormatformatter=newSimpleDateFormat("yyyy-MM-dd");
- StringformattedDate=formatter.format(value);
- jgen.writeString(formattedDate);
- }
- }
然後在你的POJO上找到日期的get方法
- @JsonSerialize(using=CustomDateSerializer.class)
- publicDategetCreateAt(){
- returncreateAt;
- }