简体   繁体   English

Java Android json创建一个json

[英]Java Android json Create a json

This is my java object: 这是我的java对象:

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. 我想从对象照片创建一个json。 I did this: 我这样做:

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

But, it creates a json with all parameters. 但是,它会创建一个包含所有参数的json。 Sometimes I don't have to send GPS gps and com_id and this method put a 0 . 有时我不必发送GPS gpscom_id并且此方法放置0 I don't want to send this parameters to json. 我不想将此参数发送到json。

By default, Gson omits all fields that are null during serialization. 默认情况下,Gson忽略序列化过程中所有为空的字段。

However, primitives cannot be null so their default value will be taken which is 0(int), 0L (long), 0.0d (double), 0.0f(float). 但是,基元不能为null,因此将采用其默认值0(int),0L(长),0.0d(双精度),0.0f(浮点型)。 Try changing the field type of the primitives to their boxed equivalents Integer , Double , Long . 尝试将图元的字段类型更改为与它们对应的框式等效IntegerDoubleLong

Now, null values will be left out while the value 0 will be serialized. 现在,将保留空值,而将序列化值0

If you do want Gson to serialize null values, use new GsonBuilder().serializeNulls().create(); 如果您确实希望Gson序列化空值,请使用new GsonBuilder().serializeNulls().create();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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