您的位置:首页 > 编程语言 > Java开发

一个使用jackson转换java对象的例子

2015-04-23 16:15 357 查看
如题,以一个用户对象为例子:

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@JsonAutoDetect
/**
* 在此标记不生成json对象的属性,这里我标记了两个属性一个hibernateLazyInitializer属性,为什么要标记这个
* 属性参考前面的博文,一个password属性,出于安全这个当然不能转换成json对象了,毕竟json是在前台调用的,
* 如果你想转换的时候忽略某个属性,可以在后面继续加上
*/
@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;
}
/**
* 转换日期对象的输出格式,CustomDateSerializer 代码参考前面的博文
*/
@JsonSerialize(using = CustomDateSerializer.class)
public Date getCreateAt() {
return createAt;
}

public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
/**
* 其他的getter和setter省略
*/
}


至于中间的什么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();
// jackson
ObjectMapper mapper = new ObjectMapper();
// 把取得的用户list写入response
mapper.writeValue(response.getWriter(), list);
return null;
}
}

这样我们在浏览器访问http://yourdomain/security/user/list就可以返回一个包含所有用户信息的json数组
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: