描述:
我使用 Lombok 的 @Builder 注释来“构建”JSON 负载,然后使用 gson
将其转换为正确的 JSON 输出。
但是如何通过 builder()
方法构建数组?
代码:
RoleType RoleType = RoleType.getEnumByUserRole("Marketing");
PropertyBean PropertyBean = ConfigFactory.create(PropertyBean.class);
String defaultStore = "null";
//this is the object that's suppose to be an array.
Group group = Group.builder()
.groupId(RoleType.getGroupId())
.changedById(PropertyBean.sssUser())
.storeCode(defaultStore)
.primary(false).build();
String lastName = "QA User";
int numOfDays = 1;
String defaultLocale = "en";
User newUser = User.builder()
.firstName(RoleType.getAcronym())
.lastName(lastName)
.startDay(getCurrentYearMonthDate())
.endDay(addDaysToYearMonthDate(numOfDays))
.password(PropertyBean.tempPass())
.rightHand(true)
.operatorId("123456")
.userStores(userGroup) //<--- the userStoes object should be an array.
.locale(defaultLocale).build();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String body = gson.toJson(newUser);
System.out.println(body);
输出:
{
"firstName": "MKT_AUTO",
"lastName": "QA User",
"locale": "en",
"rightHand": true,
"startDay": "2020-02-03",
"endDay": "2020-02-04",
"operatorId": "123456",
"password": "Temp-Auto01",
"global": false,
"userStores": {
"storeCode": "null",
"groupId": 24,
"changedById": "000000081",
"primary": false
},
"active": false,
"lockedOutFlag": false
}
期望的输出
{
"firstName": "MKT_AUTO",
"lastName": "QA User",
"locale": "en",
"rightHand": true,
"startDay": "2020-02-03",
"endDay": "2020-02-04",
"operatorId": "81",
"password": "Temp-Auto01",
"global": false,
"userStores": [{ //<---- Array
"storeCode": "null",
"groupId": 24,
"changedById": "000000081",
"primary": false
}],
"active": false,
"lockedOutFlag": false
}
最佳答案
省略列表类型的 builder
的使用是可行的方法。然后只需使用 ArrayList<>()
方法就可以了。
示例:
List<Group> userStores = new ArrayList<>();
userStores.add(new Group("216", 1, "81", true));
String lastName = "QA User";
int numOfDays = 1;
String defaultLocale = "en";
User newUser = User.builder()
.firstName(RoleType.getAcronym())
.lastName(lastName)
.startDay(getCurrentYearMonthDate())
.endDay(addDaysToYearMonthDate(numOfDays))
.password(PropertyBean.tempPass())
.rightHand(true)
.operatorId("123456")
.userStores(userStores)
.locale(defaultLocale).build();
输出:
{
"firstName": "MKT_AUTO",
"lastName": "QA User",
"locale": "en",
"rightHand": true,
"startDay": "2020-02-03",
"endDay": "2020-02-04",
"operatorId": "123456",
"password": "Temp-Auto01",
"global": false,
"userStores": [
{
"storeCode": "216",
"groupId": 1,
"changedById": "81",
"primary": true
}
],
"active": false,
"lockedOutFlag": false
}
关于java - 如何使用 Lombok + Gson 创建 JSON 对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60049186/