package com.liveyc; import java.io.StringWriter; import org.junit.Test; import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liveyc.core.bean.user.Buyer; /**
* 测试类 junit + Spring
* @author lx
*
*/
public class TestJson { @Test
public void testJSON() throws Exception {
//Springmvc 课程时 @RequestBody @ResponseBody JSON与对象转换
// OOM out of memery
Buyer buyer = new Buyer();
buyer.setUsername("范冰冰");
ObjectMapper om = new ObjectMapper();
//不要NULL 不要转了
om.setSerializationInclusion(Include.NON_NULL);
StringWriter w = new StringWriter();
om.writeValue(w, buyer);
System.out.println(w.toString());
//转回对象
Buyer r = om.readValue(w.toString(), Buyer.class);
System.out.println(r);
}
}
输出:
{"username":"范冰冰"}
Buyer [Hash = 452805835, id=null, username=范冰冰, password=null, gender=null, email=null, realName=null, registerTime=null, province=null, city=null, town=null, addr=null, isDel=null, serialVersionUID=1]
如果对象中有 非常规属性 可以加 @JsonIgnore 注解给屏蔽掉
@JsonIgnore
public Integer getProductAmount(){
Integer result = 0;
//计算过程
for (BuyerItem buyerItem : items) {
result += buyerItem.getAmount();
}
return result;
}