How to get customize JSON object response in spring boot

Tags: , ,



I need to need to get customized JSON object rather than default one in Spring Boot. I could successfully get default response but I need to customize as below. Some objects needed to be converted to array and some fields should be removed.

Actual Response

{
   "packId":12,
   "packType":"sdf",
   "shortCode":"dfsdf",
   "packDescription":"fsdfd",
   "startDate":null,
   "endDate":null,
   "validityValue":30,
   "validityType":"Second",
   "expiryAction":true,
   "expiryMsg":64,
   "activationSMS":63,
   "deactivationAction":true,
   "deactivationShortCode":"fhhf",
   "deactivationSMS":64,
   "deprovisionOnExpiry":true,
   "timeBands":[
      {
         "timeBandId":1,
         "start":"10:00",
         "end":"22:00",
         "timeBand":"10:00-22:00"
      },
      {
         "timeBandId":2,
         "start":"12:00",
         "end":"20:00",
         "timeBand":"12:00-20:00"
      }
   ],
   "activationTypes":[
      {
         "activationTypeId":1,
         "name":"SMS"
      },
      {
         "activationTypeId":2,
         "name":"WEB"
      },
      {
         "activationTypeId":3,
         "name":"Channel"
      }
   ],
   "channels":[
      {
         "channelId":1,
         "name":"Hshenid"
      },
      {
         "channelId":2,
         "name":"Genisis"
      }
   ],
   "users":[
      {
         
      },
      {
         "userId":2,
         "name":"Selfcare"
      }
   ]
}

Expected Response

{
"packId": 12,
"packType": "sdf",
"shortCode": "dfsdf",
"packDescription": "fsdfd",
"startDate": null,
"endDate": null,
"validityValue": 30,
"validityType": "Second",
"expiryAction": true,
"expiryMsg": 64,
"activationSMS": 63,
"deactivationAction": true,
"deactivationShortCode": "fhhf",
"deactivationSMS": 64,
"deprovisionOnExpiry": true,
"timeBands": [
{

"start": "10:00",
"end": "22:00",

},
{

"start": "12:00",
"end": "20:00",

}
],

"activationTypes": [ "SMS","WEB","Channel"],

"channels": [ "Hshenid","Genisis","Selfcare"],

"users": [ "Selfcare" ]
}

Changes

"timeBands": [
{

"start": "10:00",
"end": "22:00",

},
{

"start": "12:00",
"end": "20:00",

}
],

"activationTypes": [ "SMS","WEB","Channel"],

"channels": [ "Hshenid","Genisis","Selfcare"],

"users": [ "Selfcare" ]

Service Class Implementation

 @Override
    public Optional<Pack> findById(int id) {
        return packRepository.findById(id);

    }

Model Class

@Id
    @GeneratedValue(strategy= GenerationType.IDENTITY )
    int packId;

    String packType;
    String shortCode;
    String packDescription;
    String startDate;
    String endDate;
    int validityValue;
    String validityType;
    Boolean expiryAction;
    int expiryMsg;
    int activationSMS;
    Boolean deactivationAction;
    String deactivationShortCode;
    int deactivationSMS;
    Boolean deprovisionOnExpiry;



    @ManyToMany(cascade = {CascadeType.MERGE})
    @JoinTable(name = "PacksTimeBands",
            joinColumns = @JoinColumn(name = "pack_id", referencedColumnName = "packId"),
            inverseJoinColumns = @JoinColumn(name = "timeband_id", referencedColumnName = "timeBandId"),
            uniqueConstraints = {@UniqueConstraint(columnNames = {"pack_id", "timeband_id"})})
    List<TimeBand> timeBands;




    @ManyToMany(cascade = {CascadeType.MERGE})
    @JoinTable(name = "PacksActivationTypes",
            joinColumns = @JoinColumn(name = "pack_id", referencedColumnName = "packId"),
            inverseJoinColumns = @JoinColumn(name = "activationtype_id", referencedColumnName = "activationTypeId"),
            uniqueConstraints = {@UniqueConstraint(columnNames = {"pack_id", "activationtype_id"})})
    List<ActivationType> activationTypes;

    @ManyToMany(cascade = {CascadeType.MERGE})
    @JoinTable(name = "PacksChannels",
            joinColumns = @JoinColumn(name = "pack_id", referencedColumnName = "packId"),
            inverseJoinColumns = @JoinColumn(name = "channel_id", referencedColumnName = "channelId"),
            uniqueConstraints = {@UniqueConstraint(columnNames = {"pack_id", "channel_id"})})
    List<Channel> channels;

    @ManyToMany(cascade = {CascadeType.MERGE})
    @JoinTable(name = "PacksUsers",
            joinColumns = @JoinColumn(name = "pack_id", referencedColumnName = "packId"),
            inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "userId"),
            uniqueConstraints = {@UniqueConstraint(columnNames = {"pack_id", "user_id"})})
    List<User> users;

Answer

Like so,

 Optional<Pack> findById(Long id);
 

Another Method to convert your expected response.

public Map<String, Objects> generateResponse(Optional<Pack> object){
    Map<String, Object> response = new HashMap<>();
    if(object.isPresent()){
        response.put("packId", object.get().getid());
        response.put("packType", object.get().getType());
        ..... put all the values that you want
    
        //For Objects you want to return in list you can do that this way
        ArrayList<?> timeBands = new ArrayList<>();
        object.get().timeBands().forEach(timeBand ->{
              Map<?> singleBand = new HashMap<>();
              singleBand.put("start", timeBand.getStart());
              singleBand.put("end", timeBand.getEnd()); 
              //Finally add this Object in list
              timeBands.add(singleBand);     
       });

      ArrayList<?> activationType = new ArrayList<>();
        object.get().timeBands().forEach(activationTypes ->{
          activationType.add(activationTime.get())
      });
      //Your arraylist to the final response Map
      response.put("key you want to keep for timeBands", timeBands);
      response.put("key you want to keep for activationType", 
      activationType);

      return response;
    }
}

For list type argument

public List<?> generateResponse(List<Pack> object){
    ArrayList<?> formattedListPacks = new ArrayList<>();
    
      object.forEach( pack ->{
        Map<String, Object> response = new HashMap<>();
        response.put("packId", object.get().getid());
        response.put("packType", object.get().getType());
        ..... put all the values that you want
    
        //For Objects you want to return in list you can do that this way
        ArrayList<?> timeBands = new ArrayList<>();
        object.get().timeBands().forEach(timeBand ->{
              Map<?> singleBand = new HashMap<>();
              singleBand.put("start", timeBand.getStart());
              singleBand.put("end", timeBand.getEnd()); 
              //Finally add this Object in list
              timeBands.add(singleBand);     
       });

      ArrayList<?> activationType = new ArrayList<>();
        object.get().timeBands().forEach(activationTypes ->{
          activationType.add(activationTime.get())
      });
      //Your arraylist to the final response Map
      response.put("key you want to keep for timeBands", timeBands);
      response.put("key you want to keep for activationType", 
      activationType);

      formattedListPacks.add(response);
      });
      return formattedListPacks;
}


Source: stackoverflow