如何在没有重复代码的情况下填充JSON对象的一部分?

时间:2019-02-07 13:53:28

标签: json swift post

我正在使用Microsoft Graph API,特别是FindMeetingTimes API。可以在此处看到:https://docs.microsoft.com/en-us/graph/api/user-findmeetingtimes?view=graph-rest-1.0

我正在使用Swift进行开发。我的JSON对象可以正常工作,并且发布成功,但是我只是想知道更改这种代码的最佳/最有效方法是什么,以便它可以消除重复的代码-特别是在JSON中添加位置。位置列表可能非常大,因此我想遍历一个位置数组并将其添加到JSON对象中。.

我的方法如下:

static func setupJsonObjectForFindMeetingTimeAllRooms(nameOfRoom: String, roomEmailAddress: String, dateStartString: String, dateEndString: String, durationOfMeeting: String) -> [String: Any] {
    let jsonObj : [String: Any] =
        [
            "attendees": [
                [
                    "type": "required",
                    "emailAddress": [
                        "name": nameOfRoom,
                        "address": roomEmailAddress
                    ]
                ]
            ],
            "locationConstraint": [
                "isRequired": "true",
                "suggestLocation": "false",
                "locations": [
                    [
                        "displayName": "First Floor Test Meeting Room 1",
                        "locationEmailAddress": "FirstFloorTestMeetingRoom1@microsoft.com"
                    ],
                    [
                        "displayName": "Ground Floor Test Meeting Room 1",
                        "locationEmailAddress": "GroundFloorTestMeetingRoom1@microsoft.com"
                    ]
                    //and the rest of the rooms below this.. how do i do this outside in a loop? to prevent repetitive code?
                ]
            ],
            "timeConstraint": [
                "activityDomain":"unrestricted",
                "timeslots": [
                    [
                        "start": [
                            "dateTime": dateStartString,
                            "timeZone": Resources.utcString
                        ],
                        "end": [
                            "dateTime": dateEndString,
                            "timeZone": Resources.utcString
                        ]
                    ]
                ]
            ],
            "meetingDuration": durationOfMeeting,
            "returnSuggestionReasons": "true",
            "minimumAttendeePercentage": "100",
            "isOrganizerOptional": "true"
    ]
    return jsonObj
}

执行此操作的最佳方法是什么?我是否只删除JSON的位置部分,并在返回之前用位置数组填充它?

我试图实现一种将位置添加到JSON的方法-使用此方法:

static func addLocationsToExistingJson(locations: [String], jsonObj: [String: Any]) -> [String: Any] {
        var  data: [String: Any] = jsonObj
        for i in stride(from: 0, to: locations.count, by: 1){
            let item: [String: Any] =  [
                "displayName": locations[i],
                "locationEmailAddress": locations[i]
            ]
            // get existing items, or create new array if doesn't exist
            var existingItems = data["locations"] as? [[String: Any]] ?? [[String: Any]]()
            // append the item
            existingItems.append(item)
            // replace back into `data`
            data["locations"] = existingItems
        }
        return data
    }

并在返回原始方法中的JSON之前调用此方法。但是,看来最终的JSON不是我想要的格式。 错误的版本如下所示:

["timeConstraint": ["activityDomain": "unrestricted", "timeslots": [["start": ["dateTime": "2019-02-07 14:00:00", "timeZone": "UTC"], "end": ["dateTime": "2019-02-07 15:00:00", "timeZone": "UTC"]]]], "minimumAttendeePercentage": "100", "isOrganizerOptional": "true", "returnSuggestionReasons": "true", "meetingDuration": "PT60M", "attendees": [["type": "required", "emailAddress": ["name": "N", "address": "TestUser6@qubbook.onmicrosoft.com"]]], "locationConstraint": ["isRequired": "true", "suggestLocation": "false"]]

工作的JSON如下所示:

["timeConstraint": ["activityDomain": "unrestricted", "timeslots": [["start": ["dateTime": "2019-02-07 14:30:00", "timeZone": "UTC"], "end": ["dateTime": "2019-02-07 15:30:00", "timeZone": "UTC"]]]], "attendees": [["type": "required", "emailAddress": ["name": "N", "address": "TestUser6@qubbook.onmicrosoft.com"]]], "minimumAttendeePercentage": "100", "locations": [["displayName": "FirstFloorTestMeetingRoom1@qubbook.onmicrosoft.com", "locationEmailAddress": "FirstFloorTestMeetingRoom1@qubbook.onmicrosoft.com"], ["displayName": "GroundFloorTestMeetingRoom1@qubbook.onmicrosoft.com", "locationEmailAddress": "GroundFloorTestMeetingRoom1@qubbook.onmicrosoft.com"]], "locationConstraint": ["isRequired": "true", "suggestLocation": "false"], "meetingDuration": "PT60M", "isOrganizerOptional": "true", "returnSuggestionReasons": "true"]

我将如何更改代码,以便将位置添加到JSON中的locationConstraint对象下,而不是仅添加到JSON中,而不是在[“ locationConstraint”]部分下?

1 个答案:

答案 0 :(得分:0)

根据Joakim的建议,您可以通过structs和Codable对json结构进行建模。例如:


    struct AdditionalData: Codable {
        let emailAdress: [String]
    }

    struct Person: Codable {
        let age: Int
        let name: String
        let additionalData: AdditionalData
    }

    let additionalData = AdditionalData(emailAdress: ["test@me.com", "foo@bar.com"])
    let p1 = Person(age: 30,
                    name: "Frank",
                    additionalData: additionalData)

    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted

    if let data = try? encoder.encode(p1),
        let jsonString = String(data: data, encoding: .utf8) {
        print(jsonString)
    }

这将导致:

{
  "age" : 30,
  "name" : "Frank",
  "additionalData" : {
    "emailAdress" : [
      "test@me.com",
      "foo@bar.com"
    ]
  }
}