我遇到了JSON和Swift 2的问题。 我从服务器获取此数组
[{"KidName":"Jacob","KidId":1,"GardenID":0},
{"KidName":"Sarah","KidId":2,"GardenID":0},
{"KidName":"Odel","KidId":3,"GardenID":0}]
我熟悉JSON,我知道它不是推荐的获取JSON的方法,因为它应该是类似的
{"someArray":[{"KidName":"Jacob","KidId":1,"gardenID":0}, .....
所以我的第一个问题是可以运行第一个JSON我发布并获取KidName号而不编辑JSON并添加一个JSON OBJECT来保存数组?
我的第二个问题是Swift 2,我怎样才能获得KidName(在我编辑JSON以获得数组的持有者之后)?
这是我的代码...(请阅读我添加的说明) 顺便说一句,我也熟悉SwiftyJSON ......
// Method I've build to get the JSON from Server, the Data is the JSON
sendGetRequest { (response, data ) -> Void in
// need to convert data to String So I can add it an holder
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
/**
after editing the str, i'm Having a valid JSON, let's call it fixedJSON
*/
let fixedJSON = "{\"kidsArray\":\(dropLast)}"
// Now I'm converting it to data back again
let jsonTodata = fixedJSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
// After Having the data, I need to convert it to JSON Format
do{
let dataToJson = try NSJSONSerialization.JSONObjectWithData(jsonTodata, options: []) as! [String:AnyObject]
//Here I'm getting the KidID
if let kidID = jsonSe["kidsArray"]![0]["KidId"]!!.integerValue {
print("kidID in first index is: \(kidID)\n")
}
//NOW trying to get the KidName which not working
if let kidname = jsonSe["kidsArray"]![0]["KidName"]!!.stringValue {
print("KidName is \(kidname)\n")
}
}
所以你可以看到,我无法获得KidName。 任何帮助都会令人欣慰。
答案 0 :(得分:0)
您可以使用以下功能获取' someArray'数组,然后使用此getStringFromJSON函数来获取' KidName'值。
func getArrayFromJSON(data: NSDictionary, key: String) -> NSArray {
if let info = data[key] as? NSArray {
return info
}
else {
return []
}
}
let someArray = self.getArrayFromJSON(YourJSONArray as! NSDictionary, key: "someArray")
func getStringFromJSON(data: NSDictionary, key: String) -> String {
if let info = data[key] as? String {
return info
}
return ""
}
let KidName = self.getStringFromJSON(someArray as! NSDictionary, key: "KidName")
希望这对你有用。