Java学习记录

以下根据后台项目合并请求!165进行记录:

一、序列化操作

ObjectMapper为jackson库中自带

1
2
3
ObjectMapper objectMapper = new ObjectMapper();
List<TableTitleIndex> tableTitleIndices = objectMapper.readValue(tableRowName, new TypeReference<List<TableTitleIndex>>() {});
ListPageParam listPageParam = objectMapper.readValue(param, ListPageParam.class);

可以将列表、实体类的json字符串序列化成相应的列表、实体类,反之亦然

1、对象与json字符串、byte数组

1
2
3
4
String jsonStr = mapper.writeValueAsString(user);
byte[] byteArr = mapper.writeValueAsBytes(user);
XwjUser userDe = mapper.readValue(jsonStr, XwjUser.class);
XwjUser useDe2 = mapper.readValue(byteArr, XwjUser.class);
注意,对象转json字符串时,对象中的NodeName首字母是大写,转出来是小写

2、list集合与json字符串

1
2
String jsonStr = mapper.writeValueAsString(userList);
List<XwjUser> userListDes = mapper.readValue(jsonStr, List.class);

3、map与json字符串

1
2
String jsonStr = mapper.writeValueAsString(testMap);
Map<String, Object> testMapDes = mapper.readValue(jsonStr, Map.class);

4、修改转换时的日期格式

1
2
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
String jsonStr = mapper.writeValueAsString(user);

二、时间类操作

Java8中推荐LocalDate LocalDateTime
具体详细请点击Java8 日期/时间(Date Time)API指南
其中重点格式化及解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//Format examples
LocalDate date = LocalDate.now();
//default format
System.out.println("Default format of LocalDate="+date);
//specific format
System.out.println(date.format(DateTimeFormatter.ofPattern("d::MMM::uuuu")));
System.out.println(date.format(DateTimeFormatter.BASIC_ISO_DATE));

LocalDateTime dateTime = LocalDateTime.now();
//default format
System.out.println("Default format of LocalDateTime="+dateTime);
//specific format
System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")));
System.out.println(dateTime.format(DateTimeFormatter.BASIC_ISO_DATE));

Instant timestamp = Instant.now();
//default format
System.out.println("Default format of Instant="+timestamp);

//Parse examples
LocalDateTime dt = LocalDateTime.parse("27::Apr::2014 21::39::48",DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss"));
System.out.println("Default format after parsing = "+dt);

运行结果

1
2
3
4
5
6
7
8
Default format of LocalDate=2014-04-28
28::Apr::2014
20140428
Default format of LocalDateTime=2014-04-28T16:25:49.341
28::Apr::2014 16::25::49
20140428
Default format of Instant=2014-04-28T23:25:49.342Z
Default format after parsing = 2014-04-27T21:39:48

参考

ObjectMapper使用
Java 8 Date – LocalDate, LocalDateTime, Instant
Java8 日期/时间(Date Time)API指南