how to config gson to exclude 0 integer values

前端 未结 4 1415
囚心锁ツ
囚心锁ツ 2020-12-18 21:41

I\'ve a Java class with lot of integer fields and when I want to serialize them to json string due to some of them could have no value, hence after serializing all integers

4条回答
  •  借酒劲吻你
    2020-12-18 22:22

    Create this JSON type adapter. It can be used where ever you want to ignore writing zero values. It can also be adapted to Long, Double and other numeric types. You can also change it to ignore writing a value other than zero.

    Yes I know Autoboxing and Unboxing is implicitly used but you can't specify a primitive type for the generic type.

    public class IntIgnoreZeroAdapter extends TypeAdapter {
        private static Integer INT_ZERO = Integer.valueOf(0);
    
        @Override
        public Integer read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return 0;
            }
    
            return in.nextInt();
        }
    
        @Override
        public void write(JsonWriter out, Integer data) throws IOException {
            if (data == null || data.equals(INT_ZERO)) {
                out.nullValue();
                return;
            }
    
            out.value(data.intValue());
        }
    }
    

    Change your class to specify the IntIgnoreZeroAdapter for the int members.

    class Example {
       String title = "something";
    
       @JsonAdapter(IntIgnoreZeroAdapter.class)
       int id = 22;
    
       @JsonAdapter(IntIgnoreZeroAdapter.class)
       int userId;
    } 
    

提交回复
热议问题