访问嵌套的JSON [String:Any]对象并将其附加到

时间:2019-02-08 09:09:11

标签: json swift dictionary

我正在使用Swift尝试访问JSON的“ locationConstraint”部分中的“ locations”对象,如下所示:

        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@onmicrosoft.com"
                        ],
                        [
                            "displayName": "Ground Floor Test Meeting Room 1",
                            "locationEmailAddress": "GroundFloorTestMeetingRoom1@onmicrosoft.com"
                        ]
                        //and the rest of the rooms below this.. 
                    ]
                ],
                "meetingDuration": durationOfMeeting,
        ]

我正在尝试从此方法之外将项目添加到位置(以防止重复代码,因为位置列表可能很大)-但是在替换回json的这一部分时遇到问题。

我这样做的方法:

static func setupJsonObjectForFindMeetingTimeAllRoomsTest(nameOfRoom: String, roomEmailAddress: String, dateStartString: String, dateEndString: String, durationOfMeeting: String, locations: [String]) -> [String: Any] {
    let jsonObj : [String: Any] =
        [
            "attendees": [
                [
                    "type": "required",
                    "emailAddress": [
                        "name": nameOfRoom,
                        "address": roomEmailAddress
                    ]
                ]
            ],
            "meetingDuration": durationOfMeeting
    ]

    let jsonObject = addLocationsToExistingJson(locations:locations, jsonObj: jsonObj)
    return jsonObject
}

以及将位置添加到现有json对象的方法:

static func addLocationsToExistingJson(locations: [String], jsonObj: [String: Any]) -> [String: Any] {
    var  data: [String: Any] = jsonObj

    let locConstraintObj = [
            "isRequired": "true",
            "suggestLocation": "false",
            "locations" : []

        ] as [String : Any]

    //try access locationConstraint part of json
    data["locationConstraint"] = locConstraintObj

    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
        //this line below wrong? I need to access data["locationConstraint]["locations"]
        //but an error occurs when i change to the above.. .how do i access it?
        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对象应如下所示:

  

[“ meetingDuration”:“ PT60M”,“ returnSuggestionReasons”:“ true”,   “与会者”:[[“电子邮件地址”:[“地址”:   “ TestUser6@qubbook.onmicrosoft.com”,“名称”:“ N”],“类型”:   “” required“]],” minimumAttendeePercentage“:” 100“,   “ locationConstraint”:[“ locations”:[[“ displayName”:“二楼测试   会议室1”,“ locationEmailAddress”:   “” FirstFloorTestMeetingRoom1@qubbook.onmicrosoft.com“],[” displayName“:   “底层测试会议室1”,“ locationEmailAddress”:   “” GroundFloorTestMeetingRoom1@qubbook.onmicrosoft.com“]],   “ suggestLocation”:“ false”,“ isRequired”:“ true”],“ timeConstraint”:   [“ activityDomain”:“ unrestricted”,“ timeslots”:[[“ start”:   [“ dateTime”:“ 2019-02-07 14:30:00”,“ timeZone”:“ UTC”],“ end”:   [“ dateTime”:“ 2019-02-07 15:30:00”,“ timeZone”:“ UTC”]]]]],   “ isOrganizerOptional”:“ true”]

如下所示:

  

[“ timeConstraint”:[“ activityDomain”:“ unrestricted”,“ timeslots”:   [[“开始”:[“ dateTime”:“ 2019-02-08 08:30:00”,“ timeZone”:“ UTC”],   “ end”:[“ dateTime”:“ 2019-02-08 09:30:00”,“ timeZone”:“ UTC”]]]]],   “ locationConstraint”:[“ suggestLocation”:“ false”,“ locations”:[],   “ isRequired”:“ true”],“参加者”:[[“ emailAddress”:[“ address”:   “ TestUser6@qubbook.onmicrosoft.com”,“名称”:“ N”],“类型”:   [required]]],“ returnSuggestionReasons”:“ true”,   “ isOrganizerOptional”:“ true”,“ minimumAttendeePercentage”:“ 100”,   “ locations”:[[“” locationEmailAddress“:   “ FirstFloorTestMeetingRoom1@qubbook.onmicrosoft.com”,“ displayName”:   “” FirstFloorTestMeetingRoom1@qubbook.onmicrosoft.com“],   [“ locationEmailAddress”:   “ GroundFloorTestMeetingRoom1@qubbook.onmicrosoft.com”,“ displayName”:   “” GroundFloorTestMeetingRoom1@qubbook.onmicrosoft.com“]],   “ meetingDuration”:“ PT60M”]

将location对象添加到JSON的locationConstraint部分之外的地方。我知道我需要像这样访问我的json的locationConstraint部分:var existingItems = data["locationConstraint"]!["locations"] as? [[String: Any]] ?? [[String: Any]](),但这会返回错误:

  

“任意”类型没有下标成员

这是我第一次使用JSON,并试图快速对其进行操作。我将如何解决此问题?

1 个答案:

答案 0 :(得分:1)

使用模型对象和Codable的解决方案

按照trojanfoe的建议,您应该使用模型对象并直接对其进行操作。

import Foundation

struct Meeting: Codable {
    var attendees: [Attendee]
    var locationConstraint: LocationConstraint
    var meetingDuration: Int
}

struct Attendee: Codable {
    var type: Type
    var emailAddress: EmailAdress

    enum `Type`: String, Codable {
        case required
    }
}

struct LocationConstraint: Codable {
    var isRequired: Bool
    var suggestLocation: Bool
    var locations: [Location]
}

struct EmailAdress: Codable {
    var name: String
    var address: String
}

struct Location: Codable {
    var displayName: String
    var locationEmailAddress: String
}

首先我们带上您的字典...

let jsonDict: [String: Any] =
    [
        "attendees": [
            [
                "type": "required",
                "emailAddress": [
                    "name": "specificName",
                    "address": "specificAdress"
                ]
            ]
        ],
        "locationConstraint": [
            "isRequired": true,
            "suggestLocation": false,
            "locations": [
                [
                    "displayName": "First Floor Test Meeting Room 1",
                    "locationEmailAddress": "FirstFloorTestMeetingRoom1@onmicrosoft.com"
                ],
                [
                    "displayName": "Ground Floor Test Meeting Room 1",
                    "locationEmailAddress": "GroundFloorTestMeetingRoom1@onmicrosoft.com"
                ]
            ]
        ],
        "meetingDuration": 1800,
]

...并对其进行序列化。

let jsonData = try JSONSerialization.data(withJSONObject: jsonDict, options: .prettyPrinted)
print(String(data: jsonData, encoding: String.Encoding.utf8))

然后我们将其解码为会议模型。

var meeting = try JSONDecoder().decode(Meeting.self, from: jsonData)

我们初始化一个新位置,并将其附加到我们的Meeting.locationConstraints.locations数组中。

let newLocation = Location(displayName: "newDisplayName", locationEmailAddress: "newLocationEmailAdress")
meeting.locationConstraint.locations.append(newLocation)

最后再次重新编码我们的模型对象。

let updatedJsonData = try JSONEncoder().encode(meeting)
print(String(data: updatedJsonData, encoding: String.Encoding.utf8))