将对象转换成json字符串/json字符串转成对象
public class TestJson {
public void testAdd() throws Exception {
TestTb testTb = new TestTb();
testTb.setName("范冰冰");
ObjectMapper om = new ObjectMapper();
om.setSerializationInclusion(Include.NON_NULL);
//将对象转换成json字符串
Writer wr = new StringWriter();
om.writeValue(wr, testTb);
System.out.println(wr.toString());
//转回对象
TestTb r = om.readValue(wr.toString(), TestTb.class);
System.out.println(r.toString());
}
}
这里我们使用了Include.NON_NULL, 如果TestTb 中属性为null 的就不给转换成Json, 从对象-->Json字符串 用的是 objectMapper.writeValue(). 从Json字符串-->对象使用的是objectMapper.readValue().