从 swift 中的字典数组中获取无效的 JSON 数组

Getting invalid JSON array from array of dictionaries in swift

我想从我拥有的数组中创建 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 格式?

您正在将 Swift CollectionType 转换为 JSON (bytes),然后再将其转换回来 (jsonObj)。

在这种情况下 bytesJSON 作为 NSDatajsonObj 是 Swift CollectionType.

所以当您 print(jsonObj) 不是在打印 JSON 时,您是在打印集合。

得到真正的JSON

print(NSString(data: bytes, encoding: NSUTF8StringEncoding))

在这里您将看到正确的 JSON 格式。

在Swift中JSON是一个字符串。不是对象。


你的代码应该是这样的:

let json = NSJSONSerialization.dataWithJSONObject(data, options: nil, error: nil)!

let jsonString = NSString(data: json, encoding: NSUTF8StringEncoding)!

println(jsonString)