God bless you Tatu! Worked like a charm!
Given below snippet, would you mind checking one more time that I am not
doing something stupid, please?
public static void main(String[] args) throws IOException {
// Create the delegate.
ObjectMapper objectMapper = new ObjectMapper();
JsonFactory jsonFactory = new JsonFactory(objectMapper);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JsonGenerator jsonGenerator = jsonFactory.createGenerator(outputStream);
NullExcludingTokenFilter tokenFilter = new NullExcludingTokenFilter();
FilteringGeneratorDelegate generatorDelegate = new
FilteringGeneratorDelegate(jsonGenerator, tokenFilter, true, true);
// Start the object.
generatorDelegate.writeStartObject();
// Write a non-empty field.
generatorDelegate.writeStringField("foo", "bar");
// Write a null-valued field.
generatorDelegate.writeFieldName("baz");
generatorDelegate.writeNull();
// Write {"x": {"y": []}}.
generatorDelegate.writeFieldName("x");
generatorDelegate.writeStartObject();
generatorDelegate.writeFieldName("y");
generatorDelegate.writeStartArray();
generatorDelegate.writeEndArray();
generatorDelegate.writeEndObject();
// End the object.
generatorDelegate.writeEndObject();
// Generate the JSON.
jsonGenerator.flush();
String json = outputStream.toString("UTF-8");
System.out.println(json);
}
private static class NullExcludingTokenFilter extends TokenFilter {
@Override
public boolean includeNull() {
return false;
}
}
On Saturday, October 13, 2018 at 11:21:02 PM UTC+2, Tatu Saloranta wrote:
>
> On Sat, Oct 13, 2018 at 1:22 PM Volkan Yazıcı <[email protected]
> <javascript:>> wrote>
>
> > While using `JsonGenerator`, how can I exclude empty/null/blank object
> fields?
> >
> > (I have asked the very same question on SO as well, but could not get
> any answer yet. Hence the cross-post.)
>
> By not writing them.
>
> That is, generator writes exactly what you ask it to. It is possible
> to implement a `JsonGeneratorDelegate`
> that could block calls, and in fact `FilteringGeneratorDelegate` does
> this to allow structural exclusion/inclusion.
>
> -+ Tatu +-
>
--
You received this message because you are subscribed to the Google Groups
"jackson-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
For more options, visit https://groups.google.com/d/optout.