'How to ignore a JsonProperty just for a given single endPoint and let it works for others

I have two endPoints that returns this Json :

 "type": {
      "nbrCurrentRemainingDays": 0,
      "desc": "put desc here !",
      "id": 32
    }

I need to make it ignore the desc for the first endPoint and let it for the second , is there any solution other than creating another ResponseDTO ? @jsonIgnore will ignore the property for all endPoints.


For the first endPoint : no desc

 "type": {
      "nbrCurrentRemainingDays": 0,
      "id": 32
    }

For the second : with desc

"type": {
      "nbrCurrentRemainingDays": 0,
      "desc": "put desc here !",
      "id": 32
    }


Solution 1:[1]

@JsonInclude(Include.NON_EMPTY) should do the trick.

Include.NON_EMPTY: Indicates that only properties that are not empty will be included in JSON.

The simplest solution,

Root.java

public class Root {
    public Type type;
    //Todo getter setter constructor
}

Type.java

public class Type {

    public int nbrCurrentRemainingDays;

    @JsonInclude(Include.NON_EMPTY)
    public String desc;
    public int id;

//Todo getter setter constructor
}

MyController.java

@RestController
public class MyController {

    @GetMapping("/all-fields")
    public Root test1() {

        Root root = new Root();
        Type type = new Type();
        type.setNbrCurrentRemainingDays(0);
        type.setId(32);
        type.setDesc("put desc here !");
        root.setType(type);
        return root;
    }

    @GetMapping("/ignore-desc")
    public Root test2() {

        Root root = new Root();
        Type type = new Type();
        type.setNbrCurrentRemainingDays(0);
        type.setId(32);
        type.setDesc("put desc here !");
        root.setType(type);

        //Set null value 
        type.setDesc(null);
        return root;
    }
}

Endpoint 1:localhost:8080/all-fields(with desc)

  {
    "type": {
        "nbrCurrentRemainingDays": 0,
        "desc": "put desc here !",
        "id": 32
    }
}

Endpoint 2: localhost:8080/ignore-desc(no desc)

  {
    "type": {
        "nbrCurrentRemainingDays": 0,
        "id": 32
    }
}

Solution 2:[2]

use @JsonIgnore annotation for the field and create a manual getter and setter for the desc field where the setter will be returned based on the field value.

The setter, Getter method needs to be annotated with @JsonProperty, Now setter will return the value based on the URL path (or any condition based on your choice).

Solution 3:[3]

I know a solution for this. You can extend the Json Serializer class and override the serialize method in it. You can disable the fields you don't want in it. just like this

JsonView

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 kushal agrawal
Solution 3 Meric Cana