如何用Jackson解析一个JSON输入流到一个新的流



我有一个包含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();

我如何解析json流到一个新的Stream<Person>使用杰克逊没有在内存中的所有数据?

你可以这样做

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);

}
}
}

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

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);
}