lundi 21 octobre 2019

How to design multiple objects as shown in JSON under same class?

I have a requirement where I need to implement a JSON response like below,

{
  "group":{
    "name": "MyGroup"
  }
  "members": {
    "member1" : {
      "memberCity": "Mumbai",
      "memberName": "Ajay"
    },
    "member2" : {
      "memberCity": "Banglore",
      "memberName": "Vijay"
    },
    "member3" : {
      "memberCity": "Chennai",
      "memberName": "Sujay"
    }
}

What I am doing right now is I have the response model which takes in both the classes, Group Members

Members class has multiple Member objects like below,

public class Members{

@JsonProperty("member1")
private Member member1;

@JsonProperty("member2")
private Member member2;

@JsonProperty("member3")
private Member member3;

//getters and setters
}

When I am saving the group, I am getting the group object back and fetching the members, creating new ones, setting them up and setting them back to response.

Set<MemberEntity> createdGroupMembers = createdGroup.getMembers();
Members allGroupMembers = new Members();
List<Member> allMembers = new ArrayList<>();

for (MemberEntity mem : createdGroupMembers) {
Member groupMember = new Member();
groupMember.setMemberName(mem.getMemberName();
groupMember.setMemberCity(mem.getMemberCity();
allMembers.add(groupMember);
}

allGroupMembers.setMember1(allMembers.get(0));
allGroupMembers.setMember2(allMembers.get(1));

response.setMembers(allGroupMembers);

But I don't think this is a good way to implement this. Any suggestions about how this can be implemented in a better way?

Thanks for your help.

Aucun commentaire:

Enregistrer un commentaire