使用SwiftyJSON从JSON读取数据时获得Null

时间:2016-05-24 07:34:09

标签: ios json swift rest swifty-json

我正在从两个地方读取JSON 1)来自文件和2)来自url。 这是我的JSON文件

{
"People": {

    "Person1" : {

        "Name" : "Umair",
        "Age" : "22"
    },

    "Person2" : {

        "Name" : "Rehman",
        "Age" : "28"
    },

    "Person3" : {

        "Name" : "Saqib",
        "Age" : "32"
    },

    "Person4" : {

        "Name" : "Fahad",
        "Age" : "18 "
    },

  }
}

这就是我使用SwiftyJson

读取它的方式
let path: String = NSBundle.mainBundle().pathForResource("jsonFile", ofType: "json") as String!
let jsonData = NSData(contentsOfFile: path) as NSData!
let readableJSON = JSON(data: jsonData, options: .MutableContainers, error: nil)
var myName = readableJSON["People","Person1","Name"]
print(myName)

结果它给我这个名字没有问题。当我尝试使用相同的方法从url获取Json时,我获得了完整的Json文件,但是当我尝试获取特定字段时,它返回null。这是我的代码

    let url = NSURL(string: "http://api.randomuser.me/")
    let session = NSURLSession.sharedSession()
    session.dataTaskWithURL(url!, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in

        // Make sure we get an OK response
        guard let realResponse = response as? NSHTTPURLResponse where
            realResponse.statusCode == 200 else {
                print("Not a 200 response")
                return
        }

        // Read the JSON                
            let readableJSONFromWeb = JSON(data: data!, options: .MutableContainers, error: nil)
            var origin = readableJSONFromWeb["results"]
            print(origin)


    }).resume()
}

按照上面的代码我得到了这个输出

Umair
[
 {
  "id" : {
   "name" : "SSN",
   "value" : "026-36-3780"
 },
"nat" : "US",
"cell" : "(862)-296-4803",
"phone" : "(528)-560-7652",
"login" : {
  "username" : "ticklishmouse295",
  "password" : "julie",
  "sha256" : "01234103cae3a10c5813a7c5dfd069e2533860cf2786df4dc31a501eb66b9c37",
  "sha1" : "46fa91a26c5219823b0c4a2c0fd99d390c997cd9",
  "salt" : "aU4VTMOV",
  "md5" : "be3f89edd4f22f333433d2424cbf4a95"
},
"registered" : 1144149087,
"dob" : 1170844810,
"picture" : {
  "large" : "https:\/\/randomuser.me\/api\/portraits\/women\/40.jpg",
  "thumbnail" : "https:\/\/randomuser.me\/api\/portraits\/thumb\/women\/40.jpg",
  "medium" : "https:\/\/randomuser.me\/api\/portraits\/med\/women\/40.jpg"
},
"location" : {
  "state" : "north carolina",
  "street" : "9402 mcclellan rd",
  "city" : "arvada",
  "postcode" : 93836
},
"email" : "ethel.palmer@example.com",
"gender" : "female",
"name" : {
  "title" : "mrs",
  "first" : "ethel",
  "last" : "palmer"
}
}
]

但是当我尝试使用

获取特定字段时
var origin = readableJSONFromWeb["results","location"]

我得到回报

1 个答案:

答案 0 :(得分:2)

使用SwiftyJSON进行订阅:

var origin = readableJSONFromWeb["results","location"]

仅在整个路径由词典组成时才有效。

但是您的results密钥包含数组,因此您必须传递要获取的数组项的索引。

从数组中获取第一项的示例:

var origin = readableJSONFromWeb["results",0,"location"]

结果:

{
  "city" : "sittard-geleen",
  "postcode" : 85004,
  "street" : "4774 pieterskerkhof",
  "state" : "flevoland"
}