我试图将json对象发送到服务器。服务器期望对象采用以下格式:
{
"Lat": 10.33688590000001,
"Name": "nameOfSomething",
"Lng": 58.43135800000005
}
但是我在定义对象后得到的对象是:
[
"Lat": 10.33688590000001,
"Name": nameOfSomething, //this is missing ""
"Lng": 58.43135800000005
]
我使用的代码是:
let jsonObject: [String: AnyObject] = [
"Lat": lat,
"Name": nameOfSender.text!,
"Lng": lng
]
let jsonData = try! NSJSONSerialization.dataWithJSONObject(jsonObject, options: .PrettyPrinted)
任何想法如何解决这个问题?
答案 0 :(得分:0)
Please Look on this. it will give you correct answer.
/// Use this method to get JSON string from Dictionary.
///
///
/// - returns: `String` for Dictionary
func getJSONStringForDictionary(dict:[String:AnyObject]) -> String {
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: [])
if let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as? String {
return jsonString
}
// here "jsonData" is the dictionary encoded in JSON data
} catch let error as NSError {
print(error)
}
return ""
}
/* calling */
let json = self.getJSONStringForDictionary(jsonObject)
print(json)
//{
"Lat" : 10.33688590000001,
"Name" : "nameOfSomething",
"Lng" : 58.43135800000005
}