Home > Software engineering >  How to ignore a JsonProperty just for a given single endPoint and let it works for others
How to ignore a JsonProperty just for a given single endPoint and let it works for others

Time:04-19

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
    }

CodePudding user response:

@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
    }
}

CodePudding user response:

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).

  • Related