Gson: How to exclude specific fields from Serialization without annotations

后端 未结 15 1449
后悔当初
后悔当初 2020-11-22 05:39

I\'m trying to learn Gson and I\'m struggling with field exclusion. Here are my classes

public class Student {    
  private Long                id;
  privat         


        
15条回答
  •  臣服心动
    2020-11-22 06:24

    Another approach (especially useful if you need to make a decision to exclude a field at runtime) is to register a TypeAdapter with your gson instance. Example below:

    Gson gson = new GsonBuilder()
    .registerTypeAdapter(BloodPressurePost.class, new BloodPressurePostSerializer())
    

    In the case below, the server would expect one of two values but since they were both ints then gson would serialize them both. My goal was to omit any value that is zero (or less) from the json that is posted to the server.

    public class BloodPressurePostSerializer implements JsonSerializer {
    
        @Override
        public JsonElement serialize(BloodPressurePost src, Type typeOfSrc, JsonSerializationContext context) {
            final JsonObject jsonObject = new JsonObject();
    
            if (src.systolic > 0) {
                jsonObject.addProperty("systolic", src.systolic);
            }
    
            if (src.diastolic > 0) {
                jsonObject.addProperty("diastolic", src.diastolic);
            }
    
            jsonObject.addProperty("units", src.units);
    
            return jsonObject;
        }
    }
    

提交回复
热议问题