0

Per say I have an complex object like below as my rest response to the request

public class emp {
     int Id;
     String Name;
     Address address;

 }

 public Class address {
    String StreetAdress1;
    StreetAdress2;
    String AptNO;
    String Zip;
    String State;
    String Country;
  }

I just wanted to ignore nulls in class emp and Address.

My question is if I use JsonInclude on emp class would that help discarding the null in address class while sending back as an json response.

I haven't tried it yet , just had a question in my mind and wanted to ask if that would work.

How to work with Complex Json

Kishore Jetty
  • 59
  • 1
  • 8
  • 1
    Possible duplicate of [Jackson serialization: ignore empty values (or null)](https://stackoverflow.com/questions/16089651/jackson-serialization-ignore-empty-values-or-null) – Madplay May 16 '19 at 07:23
  • My question is , would it help if I include JsonInclude on the main class , would it do the same for instantiated objects of other class as well ?. the one you have showed is all about where to use it. I am asking how would it act if this is place on a complex object like the one mentioned above. – Kishore Jetty May 16 '19 at 07:35
  • What stops you from trying it and see what it does? – bkis May 16 '19 at 08:46

2 Answers2

0

if you are using Jackson, you can do it with JsonInclude annotation:

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Address {
    private String streetAdress1;
    private String aptNO;
    private String zip;
    private String state;
    private String country;
    // setter and getter
}

public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        Address address = new Address();
        address.setCountry("some-country");
        ObjectMapper mapper = new ObjectMapper();
        String       json   = mapper.writeValueAsString(address);
        System.out.println(json);
    }
}

result:

{
    "country":"some-country"
}
Lyn
  • 41
  • 1
  • 5
0

To answer this question ,

when I tried @JsonInclude(JsonInclude.Include.NON_EMPTY) is checking for both null and empty.

Kishore Jetty
  • 59
  • 1
  • 8