使用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”:“真”,
“与会者”:[[“电子邮件地址”:[“地址”:
“testuser6@qubbook.onmicrosoft.com”,“name”:“n”],“type”:
“必需”]],“最小参与度”:“100”,
“locationConstraint”:[“locations”:[“displayname”:“一楼测试”
会议室1“,”地址电子邮件地址“:
“firstfloortestmeetingroom1@qubbook.onmicrosoft.com”],[“显示名称”:
“一楼测试会议室1”,“地点电子邮件地址”:
“GroundfloorTestMeetingRoom1@qubbook.onmicrosoft.com”]],
“suggestlocation”:“false”,“isRequired”:“true”],“时间约束”:
[“activitydomain”:“unrestricted”,“timeslots”:[“start”:
[“datetime”:“2019-02-07 14:30:00”,“时区”:“UTC”],“结束”:
[“日期时间”:“2019-02-07 15:30:00”,“时区”:“UTC”]]],
“IsOrganizerOptional”:“真”]
如图所示:
[“TimeConstraint”:[“ActivityDomain”:“无限制”,“时隙”:
[[“开始”:[“日期时间”:“2019-02-08 08 08:30:00”,“时区”:“UTC”],
“end”:[“datetime”:“2019-02-08 09:30:00”,“时区”:“UTC”]]],
“locationConstraint”:[“suggestLocation”:“false”,“locations”:[],
“isRequired”:“true”],“与会者”:[“emailAddress”:[“地址”:
“testuser6@qubbook.onmicrosoft.com”,“name”:“n”],“type”:
“必选”],“returnSuggestionReasons”:“真”,
“isoorganizational”:“true”,“minimumattendeepentage”:“100”,
“位置”:[“位置电子邮件地址”:
“firstfloortestmeetingroom1@qubbook.onmicrosoft.com”,“显示名称”:
“FirstFloorTestMeetingRoom1@qubbook.onmicrosoft.com”],
[地址电子邮件地址]
“GroundfloorTestMeetingRoom1@qubbook.onmicrosoft.com”,“显示名称”:
“groundfloortestmeetingroom1@qubbook.onmicrosoft.com”]],
“会议持续时间”:“PT60M”]
在JSON的locationConstraint部分之外添加locations对象的位置。我知道我需要像这样访问json的locationconstraint部分:
var existingItems = data["locationConstraint"]!["locations"] as? [[String: Any]] ?? [[String: Any]]()
,但这将返回一个错误:类型“any”没有下标成员
这是我第一次与json合作,并试图迅速地操纵它们。我该怎么解决这个问题?
最佳答案
使用模型对象和可编码
正如特洛伊敌人所建议的,你应该使用模型对象并直接操作它们。
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))
关于json - 访问嵌套的JSON [String:Any]对象并附加到它,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54589050/