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

时间:2015-04-16 12:09:36

标签: json swift nsdictionary nsjsonserialization

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

1 个答案:

答案 0 :(得分:2)

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

在这种情况下,bytesJSON NSDatajsonObj是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)