Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/108.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Parse JSONArray包含JSONObject_Ios_Json_Swift3_Xcode8_Alamofire - Fatal编程技术网

Ios Parse JSONArray包含JSONObject

Ios Parse JSONArray包含JSONObject,ios,json,swift3,xcode8,alamofire,Ios,Json,Swift3,Xcode8,Alamofire,您好,我是swift的新成员,我从alamofire获得了一个由jsonArray组成的响应,其中包含如下JSONObject [{"id":"1","name":"person1"},{"id":"2","name":"person2"}] Alamofire.request(url).responseJSON{ response in if(response.result.isSuccess) { if let

您好,我是swift的新成员,我从alamofire获得了一个由jsonArray组成的响应,其中包含如下JSONObject

[{"id":"1","name":"person1"},{"id":"2","name":"person2"}]
Alamofire.request(url).responseJSON{ response in
            if(response.result.isSuccess)
            {
                if let jsonarray = response.result.value as? [[String: Any]] 
                    {
                      //what to do here ?
                    }
            }
        }
如何将其解析为该自定义模型的数组

class Person {
  var name : String
  var id : String
}
我做了很多搜索,但找不到与我相同的案例,也不能使用Codable,因为我使用的是xcode 8,现在无法将我的xcode版本升级到9

我得到的回应是这样的

[{"id":"1","name":"person1"},{"id":"2","name":"person2"}]
Alamofire.request(url).responseJSON{ response in
            if(response.result.isSuccess)
            {
                if let jsonarray = response.result.value as? [[String: Any]] 
                    {
                      //what to do here ?
                    }
            }
        }
对所需变量使用guard else。 是否有其他可选变量,如var age:Int?你可以亲自这样做:

for userDictionary in jsonarray{
    guard let id = userDictionary["id"] as? String, let name = userDictionary["name"] as? String else { continue }
    let age = userDictionary["age"] as? Int
    persons.append(Person(id, name, age))
}
@托尼

在swift4中,您可以对解析JSON的协议进行编码,这有助于编写通用代码。假设在未来的需求中添加dob比它简单。 在swift3中,您可以使用对象映射器类进行相同的操作


如果你需要更多的帮助,请告诉我

您是如何从url响应中获取json对象的?@ReinierMelian post使用请求正文编辑,我确实需要知道如何获取json对象您已经有了json正文,您需要知道如何将其转换为人?太好了^^这正是我需要的,非常感谢Hanks,但我已经在我的问题中强调了我不能使用Codable,@Sti确实满足了我的需要: