我将JSON解析为DTO (CryptoCoinResponse),如下所示:
{
"data":[
{
"quote":{
"USD":{
"price":35957.144434663925,
"volume_24h":22208499250,
"market_cap":684385813954
}
},
"id":"bitcoin"
}
]
}并试图使用流API将“数据”中的每个对象转换为实体。我试着做以下几件事:
public static List<CryptoCurrency> parseDtoToEntity(CryptoCoinResponse crypto){
return crypto.getData().stream()
.map(CryptoCoinResponse.Data::getQuote)
.map(CryptoCoinResponse.Quote::getUsd)
.map(usd ->
new CryptoCurrency(
data.getId(),
usd.getPrice(),
usd.getMarket_cap(),
usd.getPrice(),
LocalDateTime.now()))
.collect(Collectors.toList());
}但是,我无法从以前的映射访问id属性(data.getId())。我的解决办法如下:
public static List<CryptoCurrency> parseDtoToEntity(CryptoCoinResponse crypto){
return crypto.getData().stream()
.map(data ->
new CryptoCurrency(
data.getId(),
data.getQuote().getUsd().getPrice(),
data.getQuote().getUsd().getMarket_cap(),
data.getQuote().getUsd().getPrice(),
LocalDateTime.now()))
.collect(Collectors.toList());我在想,这样做更好吗?
提前感谢
发布于 2022-05-07 20:38:48
为了避免复制getQuote().getUSD(),我们为什么不展开单行lambda函数并在其中声明一个名为usd的变量?
crypto.getData().stream()
.map(data -> {
// Unpack USD here so that we can avoid repeating "getQuote().getUSD()" later
var usd = data.getQuote().getUsd();
return new CryptoCurrency(
data.getId(),
usd.getPrice(),
usd.getMarket_cap(),
usd.getPrice(),
LocalDateTime.now());
}).collect(Collectors.toList());如果我们想重复使用数据的其他部分,比如data.getQuote(),那么我们可以声明其他变量。
发布于 2022-05-07 18:41:17
最好的方法是使用Jackson https://mkyong.com/java/jackson-how-to-parse-json/
https://stackoverflow.com/questions/72155263
复制相似问题