Java JsonObjectBuilder adding extra 'metadata&

2019-06-06 03:22发布

问题:

I have one JsonObjectBuilder that builds my response.

I have a for loop that loops 7 times, during each iteration it builds a new JsonObjectBuilder, adds key/value pairs, then this JsonObjectBuilder instance is added to the parent Builder for my response.

As I understand it, this method should build 7 nested JsonObjects in my response object.

private void addStoreHoursResponse(Map<String,Object> response, AppConfigHelper configHelper) throws IOException {

    final String OPEN = "open";
    final String CLOSE = "close";
    final String NOTES = "notes";

    JsonObject storeHours = configHelper.getStoreHours();
    Calendar now = DateUtils.getEasternTimeZoneCalendar();
    now.set(Calendar.SECOND, 0);
    now.set(Calendar.MILLISECOND, 0);
    JsonObjectBuilder responseBuilder = Json.createObjectBuilder();

    String open, close, notes;
    for (int i = 0; i < 7; i++) {
        JsonObjectBuilder hoursBuilder = Json.createObjectBuilder();
        HoursKey hoursKey = HoursKey.getHoursKey(now);
        JsonObject hours = storeHours.getJsonObject(hoursKey.toString());

        open = hours.isNull(OPEN) ? null : hours.getString(OPEN);
        close = hours.isNull(CLOSE) ? null : hours.getString(CLOSE);
        notes = hours.isNull(NOTES) ? null : hours.getString(NOTES);

        if (open == null || close == null) {
            hoursBuilder.add(OPEN, JsonValue.NULL);
            hoursBuilder.add(CLOSE, JsonValue.NULL);
            hoursBuilder.add(NOTES, JsonValue.NULL);
        } else {
            hoursBuilder.add(OPEN, DateUtils.getIsoString(setCalendarTime(now, open)));
            hoursBuilder.add(CLOSE, DateUtils.getIsoString(setCalendarTime(now, close)));
            hoursBuilder.add(NOTES, notes);
        }
        responseBuilder.add(DateUtils.getIsoString(now), hoursBuilder);
        now.add(Calendar.DAY_OF_MONTH, 1);
    }

    response.put(STORE_HOURS, responseBuilder.build());
}

private Calendar setCalendarTime(Calendar calendar, String time) {
    String[] timeArray = time.split(":");

    int hour = Integer.parseInt(timeArray[0]);
    int minute = Integer.parseInt(timeArray[1]);

    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.MINUTE, minute);

    return calendar;
}

My JsonResponse has the 7 JsonObjects, but they should look like the following...

"open" : ISO time string,
"close" : ISO time string,
"notes" : String value

I am getting this as a result, what am I doing wrong?