【问题标题】:How can I populate part of a JSON object without repetitive code?如何在不重复代码的情况下填充 JSON 对象的一部分?
【发布时间】:2019-02-07 13:53:28
【问题描述】:

我正在使用 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"] 部分下?

【问题讨论】:

  • 创建与您的 json 结构相对应的结构层次结构
  • 试试 swift Codable learn here

标签: json swift post


【解决方案1】:

正如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"
    ]
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 2021-03-15
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 2016-02-07
    • 2017-11-22
    相关资源
    最近更新 更多