4

I have a POJO that is similar to:

public class MyGsonPojo {

    @Expose
    @SerializedName("value1")
    private String valueOne;

    @Expose
    @SerializedName("value2")
    private boolean valueTwo;

    @Expose
    @SerializedName("value3")
    private int valueThree;

    // Getters and other stuff here
}

The issue is that this object has to be serialized into a json body for a call to the server. Some fields are optional for the request and if I even send it with default and null values, the API responds differently (Unfortunately changing the api is not an option).

So basically I need to exclude fields from serialization if any of them is set to a default value. For example if the field valueOne is null the resulting json should be:

{
    "value2" : true,
    "value3" : 2
}

Any idea how to make this a painless effort? I wouldn't want to build the json body manually.

Any help would be great. Thank you in advice.

Serj Lotutovici
  • 4,370
  • 5
  • 32
  • 41

2 Answers2

3

Steps to follow:

  • Convert the JSON String into Map<String,Object> using Gson#fromJson()
  • Iterate the map and remove the entry from the map which are null
  • Form the JSON String back from the final map using Gson#toJson().

I have already posted the sample code in the same context here:

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
3

Option 1) Use a TypeAdapter, see accepted answer here:

Option 2) If using Jackson instead of gson is a possibility, you can annotate/serialize on getters instead of on fields, and put your logic for returning whatever you need for "default values" in your getters.

//won't get serialized because it's private 
private String valueOne;
...
@JsonSerialize
String getValueOne(){
   if (valueOne == null) return "true"
   else...
}

You could also use a single @JsonInclude(Include.NON_NULL) or @JsonInclude(Include.NON_EMPTY) annotation at the top of your class to prevent any null or empty fields from being serialized.

Community
  • 1
  • 1
drew moore
  • 31,565
  • 17
  • 75
  • 112
  • Thx, for your answer. Unfortunately Jackson is not an option (to many objects to refactor). And TypeAdapter can be excluded if the object has like 10 or even 15 fields. – Serj Lotutovici Jun 06 '14 at 21:23
  • @SerjLotutovici What do you mean "can be excluded"? – drew moore Jun 06 '14 at 21:26
  • "Can be excluded" as a solution. I don't imagine any one who would try to write a TypeAdapter for an object with 15 fields - to many chances that you will make a mistake. But thx for the Jackson tip - will consider it in my next project. – Serj Lotutovici Jun 06 '14 at 21:30
  • 1
    Ah, well yes I'd agree with you there, if that's the case. I'd look at @Braj's first solution – drew moore Jun 06 '14 at 21:34