Home > Software design >  JSON parsing with {} in Java
JSON parsing with {} in Java

Time:11-11

I am looking for the simplest answer to the given problem statement.

class X{
  Address add;
}
class Address{
 String str;
 String pincode;
}

The request is formed with x object as :

X:{
 add : {} //when none of the fields(str, pincode) present & they do not have any value
}

Now , I do not want to send address: {} in the payload.

Any JSON annotations will do this job?

I tried with @JsonInclude(JsonInclude.Include. NON_NULL) but not helpful to avoid the field.

CodePudding user response:

You can try @JsonIgnore annotation

class X{
  @JsonIgnore
  Address add;
}

CodePudding user response:

You can use Include.CUSTOM to define a custom filter, which will use the equals() method.

Since CUSTOM will instantiate the object using the default constructor and use equals(), you can simply specify the value class itself as the filter, if it implements a sane equals method:

class X{
    @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = Address.class)
    public Address add;
}
class Address{
    public String str;
    public String pincode;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Address address = (Address) o;
        return Objects.equals(str, address.str) && Objects.equals(pincode, address.pincode);
    }

    @Override
    public int hashCode() {
        return Objects.hash(str, pincode);
    }
}

Note that this will however produce add: null when add is null. To avoid that, you can put it into a real custom filter:

class X{
    @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = AddressFilter.class)
    public Address add;
}

class AddressFilter {
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return true;
        }
        if (!(obj instanceof Address)) {
            return false;
        }
        Address add = (Address) obj;
        return add.str == null && add.pincode == null;
    }
}
  • Related