0

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;
1
  • You can use HashMap to do that! First Take a HashMap for response and then add the ArrayList Objects and HashMap Objects to the response to format JSON accordingly Commented Aug 25, 2020 at 4:56

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

@Amith Mishra How can I assign Json object values to array "activationTypes": [ "SMS","WEB","Channel"] = Json Object "channels": [ "Hshenid","Genisis","Selfcare"] = Json Object "users": [ "Selfcare" ] = Json Object
Please check the updated answer and in same way you can add other objects as well
How can I use your solution for List<Pack>
@Amith Mishra. list type argument code not working since error got list cannot be converted to map
You just needed to change the return type. This is so basics, please try to resolve the basic issues at your end as much as possible because it will help you to grow :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.