如何从字典数组中按键选择数据?

时间:2016-10-15 03:48:39

标签: json swift dictionary

我尝试按键从数组字典中选择数据。
我可以做索引编号。
但这里是我的字典[[String : AnyObject]]什么是当我从json反序列化到字典时,存储每个元素。
因为字典设置键值对,字典中的每个值都与唯一键相关联。

这是我的Json:

{
  "photos":  {
    "page": 1,
    "pages": 1,
    "perpage": 500,
    "total": 36,
    "photo":  [
       {
        "id": "9671201784",
        "owner": "34507951@N07",
        "secret": "fb55a848bc",
        "server": "5494",
        "farm": 6,
        "title": "Burning Man 2013",
        "ispublic": 1,
        "isfriend": 0,
        "isfamily": 0,
        "url_m": "https://farm6.staticflickr.com/5494/9671201784_fb55a848bc.jpg",
        "height_m": "333",
        "width_m": "500",
        "is_primary": 1,
        "has_comment": 0
      },
       {
        "id": "16553346708",
        "owner": "116399434@N04",
        "secret": "092f304f0e",
        "server": "7630",
        "farm": 8,
        "title": "Burning Man",
        "ispublic": 1,
        "isfriend": 0,
        "isfamily": 0,
        "url_m": "https://farm8.staticflickr.com/7630/16553346708_092f304f0e.jpg",
        "height_m": "244",
        "width_m": "500",
        "is_primary": 0,
        "has_comment": 0
      }],
 "stat": "ok"
}

反序列化swift代码;

if let photos = parsedResult[Constants.FlickerResponseKeys.Photos] as?[String : AnyObject ]{

    //  print(photos[Constants.FlickerResponseKeys.Photo])
    if let photo = photos[Constants.FlickerResponseKeys.Photo] as? [[String : AnyObject]] {
        print(photo[0])                    
    }
}

2 个答案:

答案 0 :(得分:0)

将其放在照片中

for (key, value) in photo {
 print(key)
 print(value)
}

答案 1 :(得分:0)

您可以轻松地将JSON映射到ObjectMapper。创建一个新的swift文件并输入以下代码,

import UIKit
import ObjectMapper


class Photos: Mappable  {

var page : Int
var pages : Int
var perpage : Int
var total : Int

var photo : [MyPhoto]

required init?(_ map: Map) {

    page = 0
    pages = 0
    perpage = 0
    total = 0

    photo = []
}

func mapping(map: Map) {

    page                    <- map["photos.page"]
    pages                   <- map["photos.pages"]
    perpage                 <- map["photos.perpage"]
    total                   <- map["photos.total"]

    photo                   <- map["photos.photo"]
  }
}


class MyPhoto: Mappable {

var id : String
var owner : String
var secret : String
.
.
.

required init?(_ map: Map) {

    id = ""
    owner = ""
    secret = ""
}

func mapping(map: Map) {

    id                          <- map["id"]
    owner                       <- map["owner"]
    secret                      <- map["secret"]

}
}

这就是你将如何使用它。

if let data = Mapper<Photos>().map(result){
    print(data.perpage)
    print(data.photo.count)
    // do something with your data
}

如果您发现任何困难,请告诉我。