Java JsonObjectBuilder adding extra 'metadata' when added as child to JsonObjectBuilder

久未见 提交于 2019-12-08 02:47:54

问题


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?

来源:https://stackoverflow.com/questions/35191003/java-jsonobjectbuilder-adding-extra-metadata-when-added-as-child-to-jsonobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!