4

I would like to remove empty string by using toJson from GSON. Example object:

public class ExampleObject {
    String defaultEmpty = "";
    String example;

    public ExampleObject() {
        this.example = "foo";
    }

and after

using

new Gson().toJson(new ExampleObject());

I am receiving

  "defaultEmpty " : "",
   "position" : "foo"

Is there any way to not including empty string during deserialization? I know GSON is ignoring null, but sometimes I have an empty string in my object and I have to ignore it.

logi-kal
  • 7,107
  • 6
  • 31
  • 43
kamil wilk
  • 117
  • 7

1 Answers1

0

Here is a simplified example.

static class ExampleObjectSerializer implements JsonSerializer<ExampleObject> {

    @Override
    public JsonElement serialize(ExampleObject src, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject object = new JsonObject();
        object.addProperty("example", src.example);
        if(src.defaultEmpty != null && !src.defaultEmpty.equals("")) {
            object.addProperty("defaultEmpty", src.defaultEmpty);
        }
        return object;
    }
}

public static void main(String[] args) {
    Gson gson = new GsonBuilder().registerTypeAdapter(ExampleObject.class, new ExampleObjectSerializer()).create();
    ExampleObject exampleObject = new ExampleObject();
    String result = gson.toJson(exampleObject);
    System.out.println(result);
}
Eugene
  • 117,005
  • 15
  • 201
  • 306