I've a Java class with lot of integer fields and when I want to serialize them to json string due to some of them could have no value, hence after serializing all integers get zero as values ! I want to config gson not to serialize them if they do not have any values.
for example I have this class :
class Example {
String title = "something";
int id = 22;
int userId;
}
by default gson gives me this result :
{
"title" : "something",
"id" : 22,
"userId" : 0
}
but i don't want the userId to be serialized when its value is 0. so the json should be:
{
"title" : "something",
"id" : 22
}
for objects by default gson doesn't serialize null objects is there a way to config gson not to serialize 0 numbers
By default, the Gson object does not serialize the fields with null values to JSON. If a field in a Java object is null, Gson excludes it. We can force Gson to serialize null values via the GsonBuilder class. We need to call the serializeNulls() method on the GsonBuilder instance before creating the Gson object.
One option is to define a custom JsonDeserializer, however better would be to not use a HashMap (and definitely don't use Hashtable!) and instead give Gson more information about the type of data it's expecting. Show activity on this post. Show activity on this post. Show activity on this post.
@SerializeName is used to set the key that json object will include ,however @Expose is used to decide whether the variable will be exposed for Serialisation and Deserialisation ,or not.
We have to just use class Integer
(Integer javadoc).
class Example {
String title = "something";
Integer id = 22;
Integer userId;
}
Create this JSON type adapter. It can be used where ever you want to ignore writing zero values. It can also be adapted to Long, Double and other numeric types. You can also change it to ignore writing a value other than zero.
Yes I know Autoboxing and Unboxing is implicitly used but you can't specify a primitive type for the generic type.
public class IntIgnoreZeroAdapter extends TypeAdapter<Integer> {
private static Integer INT_ZERO = Integer.valueOf(0);
@Override
public Integer read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return 0;
}
return in.nextInt();
}
@Override
public void write(JsonWriter out, Integer data) throws IOException {
if (data == null || data.equals(INT_ZERO)) {
out.nullValue();
return;
}
out.value(data.intValue());
}
}
Change your class to specify the IntIgnoreZeroAdapter for the int members.
class Example {
String title = "something";
@JsonAdapter(IntIgnoreZeroAdapter.class)
int id = 22;
@JsonAdapter(IntIgnoreZeroAdapter.class)
int userId;
}
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