我一直在尝试创建有效的JSON对象,但似乎无法这样做。我一直在看Create JSON Object from Class in Swift作为参考,这个人似乎让他的代码工作。我有一些非常相似的东西。这是我的尝试:
func parseExportDB() -> [Dictionary<NSString, AnyObject>]{
var exportDict: [Dictionary<NSString, AnyObject>] = []
for tuple in export {
var dictObj = [
"PhoneID": 123,
"LocLabel": tuple[crosslocation] as NSString,
"Latitude": 123,
"Longitude": -123,
"Time" : tuple[time] as NSString,
"Heading" : tuple[heading] as NSString
]
exportDict.append(dictObj)
}
return exportDict
}
这就是我调用函数的方式:
var exportList = database.parseExportDB()
exportData.sendJsonToServer(exportList)
这就是我尝试将我的JSON发送给我的服务器的POST请求:
func sendJsonToServer(ExportList: [Dictionary<NSString, AnyObject>]){
if NSJSONSerialization.isValidJSONObject(ExportList){
println("Is NOT valid JSON.")
}
var request = NSMutableURLRequest(URL: NSURL(string: "<Server link here>")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
if let serializedData = NSJSONSerialization.dataWithJSONObject(ExportList, options: nil, error: &err){
println("Export List: \(ExportList)")
if NSJSONSerialization.isValidJSONObject(ExportList){
println("Is not valid JSON again!")
}
else{
println("Valid JSON!")
}
request.HTTPBody = serializedData
println(request.HTTPBody)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
...
}
问题是当我调用第一个和第二个if NSJSONSerialization.isValidJSONObject(ExportList)
语句时,两者似乎都说ExportList
无效JSON。我不知道为什么。我查看了上面的链接,看了很多链接,他们都说有效的JSON应该是NSArray
或NSDictionary`的格式。此外,我查看了我的数据,似乎一切看起来都应该如此。任何帮助,将不胜感激。谢谢!
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Request: \(request)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as! NSArray
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
}
但是,当我尝试执行第var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as! NSArray
行时,我的数据字总是返回nil,我不完全确定为什么......有任何见解?
答案 0 :(得分:1)
你的代码是正确的但是有一点细节:
你做了if NSJSONSerialization.isValidJSONObject(ExportList){
println("Is NOT valid JSON.")
}
如果有效则显示错误???
这是错误的方式......你错过了一个
if !NSJSONSerialization.isValidJSONObject(ExportList){
println("Is NOT valid JSON.")
}