[英]Using Java 8 to convert a list of String into a list of Object
有一個從文件讀取的流,每一行的內容如下:
{"uid":"5981865218","timestamp":1525309552069,"isHot":true}
用戶類別:
public class User {
private String uid;
private long timestamp;
private boolean isHot;
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public boolean getIsHot() {
return isHot;
}
public void setIsHot(boolean isHot) {
this.isHot = isHot;
}
}
我想從文件流中獲取對象“列表”列表的代碼:
BufferedReader targetBr = null;
targetBr = new BufferedReader(new FileReader(targetUsersFile));
List<User> tmpUsers = targetBr.lines().?I don't know how process in there?.collect(Collectors.toList());
您需要將String反序列化為User
對象。 我在這里使用過Jackson Jackson ObjectMapper (您可以很好地使用Gson等其他產品)。
ObjectMapper objectMapper = new ObjectMapper();
...
targetBr.lines()
.map(line -> {
try {
return objectMapper.readValue(line, User.class);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}).collect(Collectors.toList());
流的map
部分帶有一個Function
,因此您不能從那里拋出一個檢查異常。 因此,我將Jackson的readValue
拋出(可能拋出)的IOException
封裝到RuntimeException中。 您可能需要根據需要更改該部分。
這只是一個開始。 考慮當存在無法反序列化為User
的無效條目時該怎么辦。 一些特定的極端情況:
UnrecognizedPropertyException
異常。 您可以找到忽略它的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.