Jackson将实体转为json形式,且未空或者null(不参加序列化)

Jackson将实体转为json形式,且未空或者null(不参加序列化),
常见用法:
ObjectMapper mapper=new ObjectMapper().setSerializationInclusion(JsonIclude.Inculde.NON_NULL)
常见还有:Include.ALAWAYS 默认;NON_DEFAULT 默认不序列化
NON_EMPTY 属性为空("")或者null都不序列化 NON_NULL null不序列化

除了这种写成注解形式。
依赖jar包:jackson-core,jackson-annotations
①writeValue() ----------convert object to json in file

ObjectMapper mapper =new ObjectMapper();
stall obj=new stall();
//[object to Json in file]  
 Mapper.writeValue(new File("c:\\file.json"),obj);
//[Object to json in string]
 String jsonInString =mapper.writeValueAsString(obj);

//配置文件申明 declares Jackson-databind(查明)

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.0</version>
</dependency>

②readValue()-------convert json to object

ObjectMapper mapper =new ObjectMapper();
String jsonInString ={“name”:"mkyang"};
//json from file to object	
staff obj=mapper.readValue(new File("c:\\file.json"),satfficlass);
//json from URL to Object
staff obj=mapper.readValue(new URL("http:mkyang.com/api/staff.json"),staff.class);
//json from string to object
staff obj=mapper.readValue(jsonInString,staff.class)

猜你喜欢

转载自blog.csdn.net/weixin_42603009/article/details/87484357