【发布时间】:2020-02-04 01:01:07
【问题描述】:
说明:
我正在使用 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
}
【问题讨论】:
标签: java json gson rest-assured lombok