标签:
maven依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.1</version>
</dependency>
直接上代码:
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.tqmall.grace.entity.rabbitmq.SaleLogBo; import org.junit.Test; import java.io.IOException; import java.util.Date; /** * Created by tom_plus on 16/8/26. */ public class JsonTest { @Test public void BoToJson() { SaleLogBo logBo = new SaleLogBo(); logBo.setId(1); logBo.setBillNo("xj383833"); logBo.setShippingName("国际快递"); logBo.setGmtCreates("2016-08-09"); logBo.setUpdateDate(new Date()); ObjectMapper objectMapper = new ObjectMapper(); try { String st = objectMapper.writeValueAsString(logBo); try { SaleLogBo bo = objectMapper.readValue(st, SaleLogBo.class); System.out.println(bo.getBillNo()+">>>>>"); System.out.println("id:"+bo.getId()); } catch (IOException e) { e.printStackTrace(); } System.out.println(st); } catch (JsonProcessingException e) { e.printStackTrace(); } } }
@Data public class SaleLogBo implements Serializable{ private Integer warehouseId; @JsonProperty("sale_id") private Integer id; private Integer payType; private Integer shippingId; private String shippingName; private String comment; private BigDecimal shippingFee; @JsonIgnore private String gmtCreates; private Integer creator; private Integer shopId; private Integer orderFlag; private String billNo; private String logisticsName; private Integer billStatus; @JsonFormat(pattern = "yyyy年MM月dd日 HH时mm分ss秒",timezone="GMT+8") private Date updateDate; }
跑main函数运行结果:
billNo:xj383833
id:1
{"warehouseId":null,"payType":null,"shippingId":null,"shippingName":"国际快递","comment":null,"shippingFee":null,"creator":null,"shopId":null,"orderFlag":null,"billNo":"xj383833","logisticsName":null,"billStatus":null,"updateDate":"2016年08月26日 17时50分45秒","sale_id":1}
注解解析:
@JsonProperty,在把bo转成json的时候,如果要修改某些属性的名字,可以使用。
@JsonIgnore bo转成json的时候,进行序列化的时候忽略标记该注解的属性。
@JsonFormat 格式转化,例如@JsonFormat(pattern = "yyyy年MM月dd日 HH时mm分ss秒",timezone="GMT+8")
,其中要加上timezone="GMT+8",代表北京时间,否则将合北京时间差一天。
标签:
原文地址:http://www.cnblogs.com/tom-plus/p/5811353.html