@JsonAutoDetect (class)
这是作用于类的annotation,主要用于指明该类使用annotation,并且可以自动侦测getter,setter,构造方法,以便生成json对象
@JsonIgnore (method/field):作用于方法或字段,用来表明,当生成json的时候忽略有该annotation的方法或字段
如题,以一个用户对象为例子:
- @Entity
- @Cache (usage = CacheConcurrencyStrategy.READ_WRITE)
- @JsonAutoDetect
-
-
-
-
-
- @JsonIgnoreProperties (value = { "hibernateLazyInitializer" , "password" })
- public class User
- {
- private Long id;
- private String name;
- private String password;
- private String email;
- private Date createAt;
- @Id
- @GeneratedValue (strategy = GenerationType.IDENTITY)
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this .id = id;
- }
-
-
-
- @JsonSerialize (using = CustomDateSerializer. class )
- public Date getCreateAt() {
- return createAt;
- }
-
- public void setCreateAt(Date createAt) {
- this .createAt = createAt;
- }
-
-
-
- }
- @Entity
- @Cache (usage = CacheConcurrencyStrategy.READ_WRITE)
- @JsonAutoDetect
-
-
-
-
-
- @JsonIgnoreProperties (value = { "hibernateLazyInitializer" , "password" })
- public class User
- {
- private Long id;
- private String name;
- private String password;
- private String email;
- private Date createAt;
- @Id
- @GeneratedValue (strategy = GenerationType.IDENTITY)
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this .id = id;
- }
-
-
-
- @JsonSerialize (using = CustomDateSerializer. class )
- public Date getCreateAt() {
- return createAt;
- }
-
- public void setCreateAt(Date createAt) {
- this .createAt = createAt;
- }
-
-
-
- }
- @Entity
- @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- @JsonAutoDetect
-
-
-
-
-
- @JsonIgnoreProperties(value = {"hibernateLazyInitializer", "password"})
- public class User
- {
- private Long id;
- private String name;
- private String password;
- private String email;
- private Date createAt;
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
-
-
- @JsonSerialize(using = CustomDateSerializer.class)
- public Date getCreateAt() {
- return createAt;
- }
-
- public void setCreateAt(Date createAt) {
- this.createAt = createAt;
- }
-
-
-
- }
至于中间的什么service,dao都大同小异就不记录了
转到struts2 看看一个用jackson返回json对象的action是如何写的
- @Namespace ( "/security/user" )
- public class UserAction extends ActionSupport
- {
- @Action ( "list" )
- public String list() throws Exception {
-
- List<User> list = userService.getAll();
- response = ServletActionContext.getResponse();
-
- ObjectMapper mapper = new ObjectMapper();
-
- mapper.writeValue(response.getWriter(), list);
- return null ;
- }
- }
- @Namespace ( "/security/user" )
- public class UserAction extends ActionSupport
- {
- @Action ( "list" )
- public String list() throws Exception {
-
- List<User> list = userService.getAll();
- response = ServletActionContext.getResponse();
-
- ObjectMapper mapper = new ObjectMapper();
-
- mapper.writeValue(response.getWriter(), list);
- return null ;
- }
- }
- @Namespace("/security/user")
- public class UserAction extends ActionSupport
- {
- @Action("list")
- public String list() throws Exception {
-
- List<User> list = userService.getAll();
- response = ServletActionContext.getResponse();
-
- ObjectMapper mapper = new ObjectMapper();
-
- mapper.writeValue(response.getWriter(), list);
- return null;
- }
- }
这样我们在浏览器访问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 );
- 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);
- objectMapper.getSerializationConfig().setDateFormat(myDateFormat);
- myDateFormat对象为java.text.DateFormat,具体使用清查java API
- myDateFormat对象为java.text.DateFormat,具体使用清查java API
- myDateFormat对象为java.text.DateFormat,具体使用清查java API
2.annotaion的注释方式:
先定义自己需要的格式,例如:
- import java.io.IOException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import org.codehaus.jackson.JsonGenerator;
- import org.codehaus.jackson.JsonProcessingException;
- import org.codehaus.jackson.map.JsonSerializer;
- import org.codehaus.jackson.map.SerializerProvider;
-
-
-
-
-
-
- public class CustomDateSerializer extends JsonSerializer<Date> {
-
- @Override
- public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
- SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd" );
- String formattedDate = formatter.format(value);
- jgen.writeString(formattedDate);
- }
- }
- import java.io.IOException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import org.codehaus.jackson.JsonGenerator;
- import org.codehaus.jackson.JsonProcessingException;
- import org.codehaus.jackson.map.JsonSerializer;
- import org.codehaus.jackson.map.SerializerProvider;
-
-
-
-
-
-
- public class CustomDateSerializer extends JsonSerializer<Date> {
-
- @Override
- public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
- SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd" );
- String formattedDate = formatter.format(value);
- jgen.writeString(formattedDate);
- }
- }
- import java.io.IOException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import org.codehaus.jackson.JsonGenerator;
- import org.codehaus.jackson.JsonProcessingException;
- import org.codehaus.jackson.map.JsonSerializer;
- import org.codehaus.jackson.map.SerializerProvider;
-
-
-
-
-
-
- public class CustomDateSerializer extends JsonSerializer<Date> {
-
- @Override
- public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
- SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
- String formattedDate = formatter.format(value);
- jgen.writeString(formattedDate);
- }
- }
然后在你的POJO上找到日期的get方法
- @JsonSerialize (using = CustomDateSerializer. class )
- public Date getCreateAt() {
- return createAt;
- }
更多可以参考:http://wiki.fasterxml.com/JacksonAnnotations