简体   繁体   中英

Ignore Null Value Fields From Rest API Response Java

In my project when i send Rest Response to Advance Rest Client It only shows Fields which Have some values and Ignores(Does not show) fields which have NULL Values or Empty values.

Part Of Code:

Gson gson=new Gson();
// firstResponse is Object which contains the values
String jsonString = gson.toJson(firstResponse);
test.saveJson(jsonString); //OR System.out.println(jsonString);            
return Response.ok(firstResponse).build(); // Response to Rest Client

Response sample To return Response.ok(firstResponse).build();

Advance rest client From web project :

{
  "Name": "smith",
  "Properties": {
    "propertyList": [
      {
        "ID": "072",
        "Number": "415151",
        "Address": "Somewhere"
      },
      {
        "ID": "151",
        "Number": "a800cc79-99d1-42f1-aeb4-808087b12c9b",
        "Address": "ninink"
      },
      {
        "ID": "269",
      },
    ],
  },
}

Now when i save this as Json String in DB or When i want to Print this to console it also prints the fiels with null or empty values:

{
  "Name": "smith",
  "Properties": {
    "propertyList": [
      {
        "ID": "072",
        "Number": "415151",
        "Address": "Somewhere"
      },
      {
        "ID": "151",
        "Number": "a800cc79-99d1-42f1-aeb4-808087b12c9b",
        "Address": "ninink"
      },
      {
        "ID": "269",
        "Number": "",
        "Address": ""
      },

    ],
  },
  "resultList" :[]
}

How can i print or save this JSON string same as response in rest client ie i dont want to print null or empty value field i just want to ignore them.

in top og entity class , try with the annotation

@JsonInclude(Include.NON_EMPTY)

this annotation don't show any empty field in your json.

Not giving you a code but here are some pointers for you:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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