Philippe Gioseffi
Philippe Gioseffi

Reputation: 1658

It it possible to jackson to not serialize a JSON entry if a certain condition is met?

I have the following JSON list:

[
    {
        "name": "John Doe The First",
        "age": 36
    },
    {
        "name": "John Doe The Second",
        "age": 10
    }
]

And the following Java record:

public record Person(String name, int age) {}

Is it possible to Jackson not parse JSON entries matching a condition such as age under 18 without writing a Consumer and filtering out these JSonNodes as indicated in this answer?

What I want is described in the third and, until now last, comment of this very answer.

EDIT:

Based on Hiran Chaudhuri's answer it makes perfect sense that is impossible to the parser to not parse the entire file which leads me to a second question. Isn't possible to Jackson, once the JsonNode is converted into a POJO, to filter these ones out based on the described conditions?

Something similar to what @JsonFilter does but not forcing developers to write a filter based on the Stream backed by the array returned nor creating a whole new filtered list, the array returned would contain just what is needed.

Upvotes: 0

Views: 160

Answers (1)

queeg
queeg

Reputation: 9394

What you are asking is to filter the entries returned from parsing the file, but you want to perform the filtering before the parser (Jackson) has had a chance to read the file. This is not possible.

You would have to scan the inputstream and detect the boy has the right age. If not, you'd want to skip that entry and perform parsing on the next entity. But would you know how many bytes to skip? All that is the work of a parser.

You you'd better parse the JSON and perform your filtering afterwards before the application starts processing it.

Upvotes: 1

Related Questions