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; /** * java日期对象经过Jackson库转换成JSON日期格式化自定义类 * @author godfox * @date 2010-5-3 */ 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); } }
public static class CustomSerializer2 extends JsonSerializer<Region> { @Override public void serialize(Region region, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { Map<String, Object> data = Maps.newHashMap(); data.put("id", region.getId()); data.put("name", region.getName()); // ... more jgen.writeObject(data); } }
@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; } @JsonSerialize(using = CustomSerializer2.class) public List<Region> getRegions() { return this.regions; } /** * 其他的getter和setter省略 */ }