【问题标题】:Using a for loop (or iteration) within a map definition to be converted to JSON在要转换为 JSON 的地图定义中使用 for 循环(或迭代)
【发布时间】: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


【解决方案1】:

据我了解,您需要的是从一组点组成流的索引,因此您可以从具有所需范围的Intstream 开始:

List<TimeSeriesRollup> dataPoints =
                IntStream.range(0, 24)
                         .mapToObj(graph::get)
                         .map(point -> new TimeSeriesRollup(point.get(0), point.get(1)))
                         .collect(Collectors.toList());

你可以给TimeSeriesRollup类一个静态工厂方法,输入Point,结果是:

  IntStream.range(0, 24)
           .mapToObj(graph::get)
           .map(TimeSeriesRollup::from)
           .collect(toList());

【讨论】:

  • 或以Point为输入参数的构造函数,然后将映射更改为TimeSeriesRollup::new
  • 我将探索这个选项。谢谢!