1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
public class Json {
private static final String demoDtoStr = "{\"stationNos\":[\"FL-HDZ001\",\"FL-HDZ002\"],\"override\":true,\"reportWeek\":21}";
private static final String stationNosStr = "[\"FL-HDZ001\",\"FL-HDZ002\"]";
// 在线字符串转数组(Array) http://www.txttool.com/t/?id=NTE0
public static void main(String[] args) throws JsonProcessingException {
JsonDTO jsonDTO = new JsonDTO();
jsonDTO.setStationNos(List.of("FL-HDZ001", "FL-HDZ002"));
jsonDTO.setOverride(true);
jsonDTO.setReportWeek(21);
// Java对象 转 json字符串
String string = new ObjectMapper().writeValueAsString(jsonDTO);
// Java对象 转 具体Java类 注意类需要构造器,否者报错
JsonDTO jsonDTO2 = new ObjectMapper().convertValue(jsonDTO, JsonDTO.class);
// Java对象 转 Map,先转string再转map
Map<String, Object> map = new ObjectMapper().readValue(demoDtoStr, new TypeReference<>() {
});
// json字符串 转 Java对象
JsonDTO jsonDTO1 = new ObjectMapper().readValue(demoDtoStr, JsonDTO.class);
// json字符串 转 List
List<String> strings = new ObjectMapper().readValue(stationNosStr, new TypeReference<>() {
});
}
@Data
public static class JsonDTO {
private List<String> stationNos;
private Boolean override = false;
private Integer reportWeek;
}
}
|