It Grunt
It Grunt

Reputation: 3378

RestController JSON Response object format

I am using Spring Boot to return data from a Repository. I would like to format my JSON so that it plays nicely with ExtJS' ajax handling. Essentially I would like to include properties to handle success/failure, count, and errorMsg along with a List of data from the repository.

I have tried by creating a ResponseDTO object that I'm returning from my Rest Controller.

@RestController
public class AdminController {

    private static final Logger logger = LogManager.getLogger(AdminController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private SecurityService securityService;

    @Autowired
    private UserValidator userValidator;

    @GetMapping("/searchUsers")
    public ResponseDTO searchUsers(String name, String active) {
        int activeFlag;
        List<User> users;
        ResponseDTO resp;
        if(active.equals("true")) {
            activeFlag = 1;
        } else activeFlag=0;

        if(StringUtils.isEmpty(name)) {
            users= userService.findAllUsers(activeFlag);
        } else {
            users= userService.findByUsernameActive(name, activeFlag);
        }   

        return new ResponseDTO(users, true);
    }
}

Here's my DTO that I use in the controller:

public class ResponseDTO {
    private boolean success;
    private int count = 0;

    private List<?> values;

    public boolean getSuccess() {
        return this.success;
    }
    public void setState(boolean st) {
        this.success=st;
    }
    public int getCount() {
        return this.count;
    }
    public void setCount(int cnt) {
        this.count=cnt;
    }

    public List<?>getValues() {
        return this.values;
    }
    public void setValues(List<?> vals) {
        this.values = vals;
    }

    public ResponseDTO(List<?> items, boolean state) {
        this.success = state;
        values = items;
        this.count = items.size();
    }
}

Here's what the JSON I get back looks like:

{
  "ResponseDTO": {
                    "success":true,
                    "count":2,
                    "values":[{obj1 } , { obj2}]
                 }
}

what I would like to get is something more like:

{
   "success" : true,
   "count" : 2,
   "values" [{obj1},{obj2}]
}

I'm using Spring Boot and Jackson annotations. I have used an annotation to ignore individual fields in the objects in the results array, but I can't find a way to unwrap the ResponseDTO object to not include the class name.

Upvotes: 0

Views: 447

Answers (1)

Karthik TU
Karthik TU

Reputation: 161

When you serialize ResponseDTO POJO, you should not get 'ResponseDTO' in the response by default. Because, the root wrap feature is disabled by default. See the doc here. If you have the below code, please remove it.

mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);

Upvotes: 1

Related Questions