【发布时间】:2025-12-05 02:05:02
【问题描述】:
我有以下代码(不起作用)定义正在转换为 JSON 的列表映射...
ObjectMapper objectMapper = new ObjectMapper();
//Set pretty printing of json
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
//Define map which will be converted to JSON
List<TimeSeriesRollup> dataPoints = null;
for(int i=1; i<24; i++){
Long xVal = graphs2.get(i).get(0);
Long yVal = graphs2.get(i).get(1);
dataPoints = Stream.of(
new TimeSeriesRollup(xVal, yVal))
.collect(Collectors.toList());
}
List<TimeSeriesGraph> dataInfo = Stream.of(
new TimeSeriesGraph("test", dataPoints))
.collect(Collectors.toList());
//1. Convert List of Person objects to JSON
String arrayToJson = objectMapper.writeValueAsString(dataInfo);
return arrayToJson;
所需的代码功能是这样的......
ObjectMapper objectMapper = new ObjectMapper();
//Set pretty printing of json
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
//Define map which will be converted to JSON
List<TimeSeriesRollup> dataPoints = null;
dataPoints = Stream.of(
new TimeSeriesRollup(xVal1, yVal1))
new TimeSeriesRollup(xVal2, yVal2))
new TimeSeriesRollup(xVal3, yVal3))
new TimeSeriesRollup(xVal, yVal))
new TimeSeriesRollup(xVal, yVal))
new TimeSeriesRollup(xVal, yVal)) etc...
.collect(Collectors.toList());
}
List<TimeSeriesGraph> dataInfo = Stream.of(
new TimeSeriesGraph("test", dataPoints))
.collect(Collectors.toList());
//1. Convert List of Person objects to JSON
String arrayToJson = objectMapper.writeValueAsString(dataInfo);
return arrayToJson;
我希望能够添加任意数量的“TimeSeriesRollup”,由方法中其他位置的变量定义。对此有何想法或见解?我可以提供任何其他信息吗?
【问题讨论】:
-
如果您在每个
TimeSeriesRollup之间加上逗号,那不是已经有效了吗? -
是的。两种代码在技术上都有效,但我想使用迭代而不是声明 30 个项目。 @DM
-
也许可以查看
java.util.stream.Stream.Builder课程?文档说“这允许通过单独生成元素并将它们添加到 Builder 来创建 Stream”。 -
将检查它。谢谢
-
什么是
graphs2?
标签: java json jackson java-stream