如何在同一个类下的JSON映射中设计多个对象?

时间:2019-10-21 15:16:00

标签: java json jackson jackson-databind jackson-modules

我有一个需要实现如下JSON响应的要求,

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

我现在正在做的是我有一个同时包含两个类的响应模型, 组 成员

Members类具有多个如下所示的Member对象,

public class Members{

@JsonProperty("member1")
private Member member1;

@JsonProperty("member2")
private Member member2;

@JsonProperty("member3")
private Member member3;

//getters and setters
}

当我保存组时,我将返回组对象并获取成员,创建新成员,进行设置并将其设置回响应。

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);

但是我认为这不是实现此目标的好方法。关于如何更好地实现这一点的任何建议?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

如果将memebers的类型更改为array,则可能更易于处理和维护。输出json将变为:

{
"group":{
"name": "MyGroup"
}
"members": [  // changed this from object to array.
"member1" : {
  "memberCity": "Mumbai",
  "memberName": "Ajay"
},
"member2" : {
  "memberCity": "Banglore",
  "memberName": "Vijay"
},
"member3" : {
  "memberCity": "Chennai",
  "memberName": "Sujay"
}
  ]
}

然后您可以将成员定义为

@JsonProperty("members")
private ArrayList<Member> membersList;

然后,使用以下方法将成员添加到该列表将更容易

membersList.add(new Member());