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