我进行了很多搜索并尽力而为,但我被困住了。
我尝试从Json请求(从Pexel API)提取字符串:
这是我提取json的代码(已导入Alamofire和SwiftyJson)
func retrieveapi () {
let apiKey = "563*****************0c7eae"
let headers: HTTPHeaders = [
"Authorization": "5********************ae",
"Accept": "application/json"
]
Alamofire.request("https://api.pexels.com/v1/search?query=Spain+query&per_page=15&page=1", headers: headers).responseJSON { response in
if let json = response.result.value {
print ("json \(json)")
}}}
print(“ json”)的日志如下
json {
"next_page" = "https://api.pexels.com/v1/search/?page=2&per_page=15&query=Spain+query";
page = 1;
"per_page" = 15;
photos = (
{
height = 2661;
id = 52062;
photographer = "tyler hendy";
src = {
landscape = "https://images.pexels.com/photos/52062/pexels-photo-52062.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=627&w=1200";
large = "https://images.pexels.com/photos/52062/pexels-photo-52062.jpeg?auto=compress&cs=tinysrgb&h=650&w=940";
large2x = "https://images.pexels.com/photos/52062/pexels-photo-52062.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940";
medium = "https://images.pexels.com/photos/52062/pexels-photo-52062.jpeg?auto=compress&cs=tinysrgb&h=350";
original = "https://images.pexels.com/photos/52062/pexels-photo-52062.jpeg";
portrait = "https://images.pexels.com/photos/52062/pexels-photo-52062.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800";
small = "https://images.pexels.com/photos/52062/pexels-photo-52062.jpeg?auto=compress&cs=tinysrgb&h=130";
square = "https://images.pexels.com/photos/52062/pexels-photo-52062.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=1200";
tiny = "https://images.pexels.com/photos/52062/pexels-photo-52062.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=200&w=280";
};
url = "https://www.pexels.com/photo/water-architecture-colourful-church-52062/";
width = 4000;
},
{ // A lot of more results....
我只想提取:
“风景”的第一个结果。
我试图将它传递给Dict,传递给数组,以使其可编码..但是它没有成功。 有人可以帮助我,告诉我如何提取“风景”的第一个(仅第一个)结果吗?
非常感谢!
编辑:找到它,并感谢您的提示!
我把它给像我一样被困住的人。
if let dictionary = response.result.value as? [String : AnyObject]{
let listData = dictionary["photos"] as! [[String : AnyObject]]
let photoDict = listData[1]
let srcDict = photoDict["src"]
let landscapeStr = srcDict!["landscape"]
print ("landscapeStr \(landscapeStr!)")
} }
答案 0 :(得分:0)
只需使用“可降解的”。
struct Post : Decodable {
var photo : Photo?
}
struct Photo : Decodable {
var source : Source?
}
struct Source : Decodable {
var landscape : String?
}
Alamofire.request("https://api.pexels.com/v1/search?query=Spain+query&per_page=15&page=1", headers: headers).responseJSON { response in
guard let data = response.results.value {
let post = createObject(json: data, decodable: Post.self)
}
}
func createObject<D: Decodable> (json : [String: Any], decodable: D.Type) throws -> D {
return try JSONDecoder().decode(decodable, from: JSONSerialization.data(withJSONObject: snapshot, options: JSONSerialization.WritingOptions.sortedKeys))
}