我正在跟随《现实世界软件开发》这本书,当前章节是关于编写一个BankStatementCSVParser
的,它可以读取如下文件:
30-01-2017,-100, Deliveroo
30-01-2017,-50, Tesco
01-02-2017,6000, Salary
02-02-2017,2000, Royalties
02-02-2017,-4000, Rent
03-02-2017,3000, Tesco
05-02-2017,-30, Cinema
并解析每一行并输出此类的对象:
public class BankTransaction {
private final LocalDate date;
private final double amount;
private final String description;
public BankTransaction(final LocalDate date, final double amount,
final String description) {
this.date = date;
this.amount = amount;
this.description = description;
}
public LocalDate getDate() {
return date;
}
public double getAmount() {
return amount;
}
public String getDescription() {
return description;
}
}
这个很好用,CSV也很容易(特别是因为我一直在抄书...),问题出现在章节末尾,当我被要求自己实现BankStatementJSONParser
时。
我已经尝试了GSON和Jackson,但由于我的BankTransaction
类是不可变的并且不允许设置器,所以我无法真正获得任何示例。
我设法让一个解决方案工作了,但它看起来很可怕:
public List<BankTransaction> parseLinesFrom(List<String> lines) {
Map<String, ?> map = new Gson().fromJson(String.join(" ", lines), Map.class);
List<?> listOfTransactions = (List<?>) map.get("transactions");
List<BankTransaction> bankTransactions = new ArrayList<>();
listOfTransactions.forEach(rawJson -> {
LinkedTreeMap<String, ?> javaJson = (LinkedTreeMap<String, ?>) rawJson;
final LocalDate localDate = LocalDate.parse(javaJson.get("date").toString(), DATE_PATTERN);
final double amount = Double.parseDouble(javaJson.get("amount").toString());
final String description = javaJson.get("description").toString();
BankTransaction newTransaction = new BankTransaction(localDate, amount, description);
bankTransactions.add(newTransaction);
});
return bankTransactions;
}
感谢任何有关如何使这个过程更少丑陋的见解,也许问题出在我自己编写的 .json 文件上:
{
"transactions": [
{
"date": "30-01-2017",
"amount": -100,
"description": "Deliveroo"
},
{
"date": "01-02-2017",
"amount": 6000,
"description": "Salary"
}
]
}
@JsonCreator
进行注释,并使用@JsonProperty
对其参数进行注释,这样是否可以解决您的问题?然后您就可以直接使用Jackson进行反序列化:objectMapper.readValue(input, List.class)
。 - knittl