我想从我拥有的数组创建JSON数组字符串。但是我得到了无效的JSON 这就是我想要的:
[
{
"validationCode": null,
"FirstName": "Samer",
"LastName": "Shame",
"MobileNumber": "0991992993",
"SimNumber": null,
"Email": null,
"PhoneNumber": "0991992994",
"Name": "Abo Alshamat",
"ID": 1
},
{
"validationCode": null,
"FirstName": "Ahmad",
"LastName": "Ali",
"MobileNumber": "0992993994",
"SimNumber": null,
"Email": null,
"PhoneNumber": "0992993995",
"Name": "AL-Kamal",
"ID": 2
}
]
这就是我得到的:
[
[
"validationCode": null,
"FirstName": "Samer",
"LastName": "Shame",
"MobileNumber": "0991992993",
"SimNumber": null,
"Email": null,
"PhoneNumber": "0991992994",
"Name": "Abo Alshamat",
"ID": 1
],
[
"validationCode": null,
"FirstName": "Ahmad",
"LastName": "Ali",
"MobileNumber": "0992993994",
"SimNumber": null,
"Email": null,
"PhoneNumber": "0992993995",
"Name": "AL-Kamal",
"ID": 2
]
]
这是代码:
var data = [NSDictionary]()
for item in someList {
var d = ["validationCode": null,
"FirstName": item.prop1,
"LastName": item.prop2,
"MobileNumber": item.prop3...]
data.append(d)
}
var bytes = NSJSONSerialization.dataWithJSONObject(data, options: NSJSONWritingOptions.allZeros, error: nil)
var jsonObj = NSJSONSerialization.JSONObjectWithData(bytes!, options: nil, error: nil) as! [Dictionary<String, String>]
我应该怎样做才能获得标准的JSON格式?
答案 0 :(得分:2)
您正在将Swift
CollectionType
转换为JSON(bytes
),然后将其转换回来(jsonObj
)。
在这种情况下,bytes
是JSON
NSData
而jsonObj
是Swift CollectionType
。
因此,当您print(jsonObj)
未打印JSON
时,您正在打印该集合。
获得真实的JSON
print(NSString(data: bytes, encoding: NSUTF8StringEncoding))
在这里,您将看到正确的JSON
格式。
在Swift中,JSON是一个String。不是一个对象。
您的代码看起来应该是这样的:
let json = NSJSONSerialization.dataWithJSONObject(data, options: nil, error: nil)!
let jsonString = NSString(data: json, encoding: NSUTF8StringEncoding)!
println(jsonString)