从可选对象(字典数组)中获取值?

时间:2018-05-23 20:16:00

标签: ios xcode swift3

我一直试图获得" name"来自使用

的回复
if let data = text.data(using: .utf8) {
    do {

        return try JSONSerialization.jsonObject(with: data, options: [])  as? [String : AnyObject]
    } catch {
        print(error.localizedDescription)
    }
}
return nil


for field in dict?["report_data"]?["name"] as? [Any] ?? [] {
    print(field)                   
}

没有成功。

回复是

  

可选({"内容":"","主题":"每周出席2018-05-14 - 2018-05-20& #34;,"附件":" []"," report_data":" [{\" name \" :\"总天数\",\"值\":\" 7 \"},{\"名称\&#34 ;:\"当前天数\",\"值\":\" 0 \"},{\"名称\&# 34;:\"总小时数",\"值\":\" .0 \"},{\"名称\ ":\"平均时数\",\"值\":\" .0 \"},{\" name \":\"开始日期\",\"值\":\" 2018-05-14 \"},{ \"名称":\"结束日期\",\"值\":\" 2018-05-20 \&# 34;}]"," asset_reference":" []"," activity_reference":" []",& #34; form_approval_field_reference":" []"})

Plz帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

实际上,您收到的回复是[String : [[String : String]]]类型的字典。因此,value密钥的"report_data"[[String : String]]类型的数组。

现在[[String : String]]实际上是一个字典数组。因此,数组的每个元素都是[String : String]的字典,其中包含"name"密钥。

let responseDictionary: [String : Any] = [ "report_data" : [
    ["name":"Total Days","value":"7"],
    ["name":"Present Days","value":"0"],
    ["name":"Total Hours","value":".0"],
    ["name":"Average Hours","value":".0"],
    ["name":"Start Date","value":"2018-05-14"],
    ["name":"End Date","value":"2018-05-20"]
] ]

if let arrayOfDictionary = responseDictionary["report_data"] as? [[String : String]] {
    for dictionary in arrayOfDictionary {
        if let name = dictionary["name"] {
            print(name)
        }
    }
}

好吧,for dictionary in arrayOfDictionary给你错误,因为当你得到它时你的回复实际上是[String : Any]类型。但是当值为Any时,您无法执行大量操作。因此,您需要将Any强制转换为显式类型才能拥有具体对象。您需要先将Any类型数组转换为实际的[[String : String]]类型数组。

修改 您注定格式错误的 JSON 。这就是你遇到麻烦的原因。请看下面如何处理DictionaryJSON

let responseDictionary: [String : Any] = [ "content": "",
                                       "subject": "Weekly Attendance 2018-05-14 - 2018-05-20",
                                       "attachments": "[]",
                                       "report_data" : [
                                            ["name":"Total Days","value":"7"],
                                            ["name":"Present Days","value":"0"],
                                            ["name":"Total Hours","value":".0"],
                                            ["name":"Average Hours","value":".0"],
                                            ["name":"Start Date","value":"2018-05-14"],
                                            ["name":"End Date","value":"2018-05-20"]
                                        ],
                                       "asset_reference": "[]",
                                       "activity_reference": "[]",
                                       "form_approval_field_reference": "[]"
                                    ]

您可能已将此词典转换为JSON,然后转换为JSON字符串。但在此过程中您丢失了JSON标准格式。如何做到这一点:

var text: String = ""

do {
    let jsonData = try JSONSerialization.data(withJSONObject: responseDictionary, options: .prettyPrinted)
    text = String(data: jsonData, encoding: .utf8) ?? ""
} catch {
    print(error.localizedDescription)
}

现在,如果您的text是有效的JSON字符串,那么您最好去:

if let data = text.data(using: .utf8) {
    do {
        let response = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
        if let response = response, let arrayOfDictionary = response["report_data"] as? [[String : String]] {
            for dictionary in arrayOfDictionary {
                if let name = dictionary["name"] {
                    print(name)
                }
            }
        }
    } catch {
        print(error.localizedDescription)
    }
}

答案 1 :(得分:0)

func dataToJSON(data: Data) -> AnyObject? {

    do {        
        return try JSONSerialization.jsonObject(with: data, options: []) as AnyObject
    }
    catch let myJSONError {

        print(myJSONError)
    }
    return nil
}

if let list = self.dataToJSON(data: data) as? [Any] {

      // here is array
}

if let list = self.dataToJSON(data: data) as? [String: Any] {

      // here is dictionary
}