Ho bisogno di dove devo convertire java object in json.Gson Serializza il campo solo se non è nullo o non vuoto
Sto utilizzando GSON per questo, ma ho bisogno del convertitore per serializzare solo valori non nulli o non vuoti.
Ad esempio:
//my java object looks like
class TestObject{
String test1;
String test2;
OtherObject otherObject = new OtherObject();
}
ora il mio esempio GSON per convertire questo oggetto per JSON sembra
Gson gson = new Gson();
TestObject obj = new TestObject();
obj.test1 = "test1";
obj.test2 = "";
String jsonStr = gson.toJson(obj);
println jsonStr;
Nella stampa sopra, il risultato è
{"test1":"test1", "test2":"", "otherObject":{}}
Qui i volevo solo che il risultato fosse
{"test1":"test1"}
Poiché test2 è vuoto e otherObject è vuoto, non voglio che vengano serializzati su dati json.
Btw, sto usando Groovy/Grails, quindi se c'è qualche plugin per questo sarebbe buono, se nessun suggerimento per personalizzare la classe di serializzazione gson sarebbe buono.
Come fa a sapere che 'otherObject' è vuoto? –