`
godfox
  • 浏览: 71370 次
  • 性别: Icon_minigender_1
  • 来自: 南宁
文章分类
社区版块
存档分类
最新评论

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

阅读更多

如题,以一个用户对象为例子:

 

@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数组

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics