Now first off, I've read some other answers on this site and others about jackson serialisation but they all provide methods for ignoring null
fields. In Java, however, int
cannot be null
.
I am trying to ObjectMap
a java object to convert to Json
but to ignore any null
fields. This works for strings but int
s end up taking on a value of 0
if uninitialised, and since 0
is not null
the field is not ignored.
private ObjectWriter mapper = new ObjectMapper().writer();
private myClass data = new myClass(); //class contains a string and int variable
data.setNumber(someInt); //set values
data.setString(someString);
String Json = mapper.writeValueAsString(data);
Can anyone shed some light on this please?
EDIT: To clarify, I have tried using the Integer
class as the data type but causes the conversion to a Json
string to throw a JsonProcessingException.
If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.
In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.
The Jackson @JsonIgnore annotation can be used to ignore a certain property or field of a Java object. The property can be ignored both when reading JSON into Java objects and when writing Java objects into JSON.
Using the Jackson JsonInclude annotation:
@JsonInclude(Include.NON_DEFAULT)
works around the problem where unassigned primitive types always assumes a default value; in this case, unassigned int
s become 0
and are subsequently ignored.
Use int wrapper Integer
. This way you'll be able to use null
value.
Alternatively you can use Jackson's JsonInclude annotation to ignore null value when serializing.
@JsonInclude(Include.NON_NULL)
public class MyClass{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With