0

This is my java object:

public class Photo {
    private String date;
    private GPS gps;
    private long task_id;
    private long pgo_id;
    private long load_id;
    private long com_id;
    private long note_id;
    private String note;
    private String path;
}

public class GPS {
    private double lon;
    private double lat;
}

And I want to create a json from object photo. I did this:

 GsonBuilder builder = new GsonBuilder();
 Gson gson = builder.create();
 String jsonObject = gson.toJson(photos);

But, it creates a json with all parameters. Sometimes I don't have to send GPS gps and com_id and this method put a 0. I don't want to send this parameters to json.

1 Answer 1

1

By default, Gson omits all fields that are null during serialization.

However, primitives cannot be null so their default value will be taken which is 0(int), 0L (long), 0.0d (double), 0.0f(float). Try changing the field type of the primitives to their boxed equivalents Integer, Double, Long.

Now, null values will be left out while the value 0 will be serialized.

If you do want Gson to serialize null values, use new GsonBuilder().serializeNulls().create();

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.