Quantcast
Viewing latest article 3
Browse Latest Browse All 5

Answer by Sotirios Delimanolis for Gson Serialize field only if not null or not empty

Create your own TypeAdapter

public class MyTypeAdapter extends TypeAdapter<TestObject>() {    @Override    public void write(JsonWriter out, TestObject value) throws IOException {        out.beginObject();        if (!Strings.isNullOrEmpty(value.test1)) {            out.name("test1");            out.value(value.test1);        }        if (!Strings.isNullOrEmpty(value.test2)) {            out.name("test2");            out.value(value.test1);        }        /* similar check for otherObject */                 out.endObject();        }    @Override    public TestObject read(JsonReader in) throws IOException {        // do something similar, but the other way around    }}

You can then register it with Gson.

Gson gson = new GsonBuilder().registerTypeAdapter(TestObject.class, new MyTypeAdapter()).create();TestObject obj = new TestObject();obj.test1 = "test1";obj.test2 = "";System.out.println(gson.toJson(obj));

produces

 {"test1":"test1"}

The GsonBuilder class has a bunch of methods to create your own serialization/deserialization strategies, register type adapters, and set other parameters.

Strings is a Guava class. You can do your own check if you don't want that dependency.


Viewing latest article 3
Browse Latest Browse All 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>