Wrapping json response in dynamic envelop - Rest api

Viewed 637

I have a simple spring-boot app with one Rest API. I want to send Student data (in JSON format)by consuming client rest web service. But I want to envelop this student info with "DATA" and that should be dynamic like below.

if(dynamic == true)
    // envelop the student information in "DATA" and send student info to client.
else 
   // Do not envelop student data and send student info to client.

Current JSON format of the student.

{
   "id": "1-abcd",
   "name": "stack",
   "address": "Pune"
}

Expected json format.

{
   "data": {
         "id": "1-abcd",
         "name": "stack",
         "address": "Pune"
     }
}

Student class is as below:

Class Student{
 String id;
 String name;
 String address;
}
2 Answers

Wrap the student object in a map if it's dynamic and return else return student object

public ResponseEntity<?> getStudent(...){
    ...
    if(dynamic){
       return ResponseEntity.status(HttpStatus.OK)
                            .body(Collections.singletonMap("data", studentObj));
    } else {
       return ResponseEntity.status(HttpStatus.OK).body(studentObj);
    }
}

You could have an Envelope class like:

public class Envelope {

    Student data;

    public Student getData() {
        return data;
    }

    public void setData(Student data) {
        this.data = data;
    }

    public Envelope(Student data) {
        super();
        this.data = data;
    }
}

And your logic in the if-else:

  // using Jackson library: import com.fasterxml.jackson.databind.ObjectMapper;
  ObjectMapper mapper = new ObjectMapper();
  Student student = new Student("1-abcd", "stack", "Pune");

  if (dynamic) {
      Envelope envelope = new Envelope(s);
      return mapper.writeValueAsString(envelope)
  }

  return mapper.writeValueAsString(student)

Output
Wrapped:

{
    "data": {
        "id": "1-abcd",
        "name": "stack",
        "address": "pune"
    }
}

Unwrapped:

{
    "id": "1-abcd",
    "name": "stack",
    "address": "pune"
}
Related