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

本文讨论了如何在用户对象中使用JPA、JSON序列化和安全性处理,包括如何标记不可序列化的属性,以及如何通过Jackson实现安全的数据转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值