简体   繁体   中英

Java Android json Create a json

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM