【问题标题】:How to parse an input stream of JSON into a new stream with Jackson如何使用 Jackson 将 JSON 的输入流解析为新流
【发布时间】:2021-10-19 07:24:03
【问题描述】:

我有一个包含 JSON 对象数组的 InputStream。可以使用 Jackson 的 ObjectMapper 将每个单独的对象解析为 Java 类 Person

public class Person {
    public String name;
    public Int age;
    ...
}

InputStream myStream = connection.getInputStream(); // [{name: "xx", age: 00}, {...}]

ObjectMapper objectMapper = new ObjectMapper();

如何使用 Jackson 将 JSON 流解析为新的 Stream<Person>,而不会将所有数据都保存在内存中?

【问题讨论】:

    标签: java json jackson java-stream


    【解决方案1】:

    你可以这样做

    private void parseJson(InputStream is) throws IOException {
    
        // Create and configure an ObjectMapper instance
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    
        // Create a JsonParser instance
        try (JsonParser jsonParser = mapper.getFactory().createParser(is)) {
    
            // Check the first token
            if (jsonParser.nextToken() != JsonToken.START_ARRAY) {
                throw new IllegalStateException("Expected content to be an array");
            }
    
            // Iterate over the tokens until the end of the array
            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
    
                // Read a contact instance using ObjectMapper and do something with it
                Person person= mapper.readValue(jsonParser, Person.class);
               
            }
        }
    }
    

    【讨论】:

    • 这看起来很有希望!但结果不是Stream<Person>,而是每个个体Person 作为变量。应该可以将它们传输到流中吗?
    • 您可以使用 Stream.of(person); 将对象传输到 Stream;
    【解决方案2】:

    SJN 的答案是正确的,但它仍然没有将 InputStream 转换为 Stream。 JsonParser 实际上有一个返回迭代器的 readValuesAs 方法。将此迭代器转换为 Stream 就很简单了。

    Stream<Person> toStream(InputStream inputStream) throws IOException {
      ObjectMapper objectMapper = new ObjectMapper();
      JsonParser jsonParser = objectMapper.getFactory().createParser(inputStream);
    
      if (jsonParser.nextToken() != JsonToken.START_ARRAY) {
        throw new IllegalStateException("Not an array");
      }
      jsonParser.nextToken(); // advance jsonParser to start of first object
      Iterator<Person> iterator = jsonParser.readValuesAs(Person.class);
    
      return StreamSupport.stream(
        Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED),
        false);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-09-24
      • 2012-11-08
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-11
      • 2017-07-09
      相关资源
      最近更新 更多