一、从URL读取JSON数据
请求远程的API,获得远程服务的JSON响应结果,并将其转换为Java POJO对象。
@Test
void testURL() throws IOException
{
URL url
= new URL("https://jsonplaceholder.typicode.com/posts/1");
ObjectMapper mapper
= new ObjectMapper();
PostDTO postDTO
= mapper
.readValue(url
, PostDTO
.class);
System
.out
.println(postDTO
);
}
注:如果不知道具体的反序列化对象是什么样的,可以把数据存到map中
Map postDTO
= mapper
.readValue(url
, Map
.class);
二、忽略某个字段
@JsonIgnore
public class {
public int value
;
@JsonIgnore
public int internalValue
;
}
disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
@Data
public class PlayerStar {
@JsonProperty("playerName")
private String name
;
private Integer age
;
private String
[] hobbies
;
private List
<String> friends
;
private Map
<String, BigDecimal> salary
;
}
@Data
public class PlayerStar2 {
@JsonProperty("playerName")
private String name
;
private String
[] hobbies
;
private List
<String> friends
;
private Map
<String, BigDecimal> salary
;
}
@Test
public void testUnKnowProperties() throws IOException
{
ObjectMapper mapper
= new ObjectMapper();
PlayerStar player
= PlayerStar
.getInstance();
String valueAsString
= mapper
.writeValueAsString(player
);
log
.info(valueAsString
);
mapper
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
PlayerStar2 playerStar2
= mapper
.readValue(valueAsString
, PlayerStar2
.class);
log
.info(playerStar2
.toString());
}
三、未赋值Java Bean序列化
如果某些类的数据可能为空,我们通常也不会为它赋值。但是客户端就是需要这个{}的JSON对象
public class MyEmptyObject {
private Integer i
;
}
可以为ObjectMapper设置disable序列化特性:FAIL_ON_EMPTY_BEANS,也就是允许对象的所有属性均未赋值。
@Test
void testEmpty() throws IOException
{
ObjectMapper mapper
= new ObjectMapper();
mapper
.disable(SerializationFeature
.FAIL_ON_EMPTY_BEANS
);
String jsonString
= mapper
.writeValueAsString(new MyEmptyObject());
System
.out
.println(jsonString
);
}
四、日期格式化
ObjectMapper mapper
= new ObjectMapper();
mapper
.disable(SerializationFeature
.WRITE_DATES_AS_TIMESTAMPS
);
mapper
.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
Map temp
= new HashMap();
temp
.put("now", new Date());
String s
= mapper
.writeValueAsString(temp
);
System
.out
.println(s
);
还可以使用注解:
@JsonFormat(pattern
= "yyyy-MM-dd HH:mm:ss",timezone
="GMT+8")
我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3vtuwevgbfms4