访问嵌套的JSON[String:Any]对象并附加到该对象
使用swift,我试图访问JSON“locationConstraint”部分中的“locations”对象,如下所示:访问嵌套的JSON[String:Any]对象并附加到该对象,json,swift,dictionary,Json,Swift,Dictionary,使用swift,我试图访问JSON“locationConstraint”部分中的“locations”对象,如下所示: let jsonObj : [String: Any] = [ "attendees": [ [ "type": "required", "emailAddress":
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对象应该如下所示:
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,
]
[“会议持续时间”:“PT60M”,“返回建议原因”:“正确”,
“与会者”:[“电子邮件地址”:[“地址”:
"TestUser6@qubbook.onmicrosoft.com,“名称”:“N”],“类型”:
“所需”],“最低参与百分比”:“100”,
“位置约束”:[“位置”:[“显示名称”:“一楼测试”
会议室1,“地点电子邮件地址”:
"FirstFloorTestMeetingRoom1@qubbook.onmicrosoft.com“],[“显示名称”:
“一楼测试会议室1”,“地点电子邮件地址”:
"GroundFloorTestMeetingRoom1@qubbook.onmicrosoft.com"]],
“suggestLocation”:“false”,“isRequired”:“true”],“timeConstraint”:
[“activityDomain”:“不受限制”,“时隙”:[[“开始”:
[“日期时间”:“2019-02-07 14:30:00”,“时区”:“UTC”],“结束”:
[“日期时间”:“2019-02-07 15:30:00”,“时区”:“UTC”]],
“同构”:“真实”]
这里看起来像这样:
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,
]
[“时间约束”:[“活动域”:“不受限制”,“时隙”:
[“开始”:[“日期时间”:“2019-02-08 08:30:00”,“时区”:“UTC”],
“结束”:[“日期时间”:“2019-02-08 09:30:00”,“时区”:“UTC”]],
“locationConstraint”:[“suggestLocation”:“false”,“locations”:[],
“isRequired”:“true”],“与会者”:[[“电子邮件地址”:[“地址”:
"TestUser6@qubbook.onmicrosoft.com,“名称”:“N”],“类型”:
“必需”],“ReturnSuggestionReasions”:“true”,
“同构”:“真实”,“最小参与百分比”:“100”,
“地点”:[[“地点电子邮件地址”:
"FirstFloorTestMeetingRoom1@qubbook.onmicrosoft.com,“displayName”:
"FirstFloorTestMeetingRoom1@qubbook.onmicrosoft.com"],
[“locationEmailAddress”:
"GroundFloorTestMeetingRoom1@qubbook.onmicrosoft.com,“displayName”:
"GroundFloorTestMeetingRoom1@qubbook.onmicrosoft.com"]],
“会议持续时间”:“PT60M”]
将locations对象添加到JSON的locationConstraint部分之外。。我知道我需要像这样访问json的locationConstraint部分:var existingItems=data[“locationConstraint”]![“地点”]作为?[[String:Any]]??[[String:Any]]()
但这将返回一个错误:
类型“Any”没有下标成员
这是我第一次使用JSON并试图用swift操纵它们。。我该如何着手解决这个问题 使用模型对象和可编码对象进行求解
正如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))
我认为您应该遵循并从JSON创建一个模型对象,您会发现它更易于操作。使用泛型集合类来表示DOM总是很难使用,因此创建特定于域的类是值得的。我建议您不要创建locationConstraint数组,然后在发送数据之前附加其他参数。另外,您需要将Any类型转换为正确的格式,如数组或字典。@Sachin Vas您能告诉我您的意思吗?如果让locations=data[“locationConstraint][“locations”]as?[[String:Any]{
您的代码在这里
}@Sachin Vas它给了我一个错误:使用“?”链接可选的,仅访问非“nil”基值的成员“subscript”,并且可选类型“Any”的值必须展开,以引用已包装基类型“Any”的成员“subscript”,然后当我将其更改为if let locations=data[“locationConstraint”]?[“locations”]作为?[[String:Any]]{}错误是:类型“Any”没有下标成员感谢解释它!