一种对象转JSON的方法

package cn.dapeng;


import java.io.IOException;
import java.io.StringWriter;


import org.junit.Test;


import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;


import cn.dapeng.core.bean.user.Buyer;




/**
 * 测试类 对象转json
 */
public class TestJson {

/**
* 对象转json
* @throws IOException 
* @throws JsonMappingException 
* @throws JsonGenerationException 
*/
@Test
public void Object2Json() throws Exception {
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());
}
}

猜你喜欢

转载自blog.csdn.net/w20228396/article/details/79445414