1 package com.liveyc; 2 3 import java.io.StringWriter; 4 5 import org.junit.Test; 6 7 import com.fasterxml.jackson.annotation.JsonInclude.Include; 8 import com.fasterxml.jackson.databind.ObjectMapper; 9 import com.liveyc.core.bean.user.Buyer; 10 11 /** 12 * 测试类 junit + Spring 13 * @author lx 14 * 15 */ 16 public class TestJson { 17 18 19 @Test 20 public void testJSON() throws Exception { 21 //Springmvc 课程时 @RequestBody @ResponseBody JSON与对象转换 22 // OOM out of memery 23 Buyer buyer = new Buyer(); 24 buyer.setUsername("范冰冰"); 25 ObjectMapper om = new ObjectMapper(); 26 //不要NULL 不要转了 27 om.setSerializationInclusion(Include.NON_NULL); 28 StringWriter w = new StringWriter(); 29 om.writeValue(w, buyer); 30 System.out.println(w.toString()); 31 //转回对象 32 Buyer r = om.readValue(w.toString(), Buyer.class); 33 System.out.println(r); 34 } 35 }
输出:
1 {"username":"范冰冰"} 2 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 注解给屏蔽掉
1 @JsonIgnore 2 public Integer getProductAmount(){ 3 Integer result = 0; 4 //计算过程 5 for (BuyerItem buyerItem : items) { 6 result += buyerItem.getAmount(); 7 } 8 return result; 9 }