Reputation: 6839
I want to create JSON array string from array that I have. But I am getting invalid JSON.
This is what I want:
[
{
"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
}
]
And this is what I get:
[
[
"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
]
]
This is code:
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>]
What I should do to get standard JSON format?
Upvotes: 1
Views: 1072
Reputation: 39091
You are converting a Swift
CollectionType
into JSON (bytes
) and then converting it back (jsonObj
).
In this case bytes
is the JSON
as NSData
and jsonObj
is a Swift CollectionType
.
So when you print(jsonObj)
you are not printing the JSON
, you are printing the collection.
To get the real JSON
print(NSString(data: bytes, encoding: NSUTF8StringEncoding))
Here you will see the proper JSON
format.
In Swift JSON is a String. Not an object.
Your code should look lie this:
let json = NSJSONSerialization.dataWithJSONObject(data, options: nil, error: nil)!
let jsonString = NSString(data: json, encoding: NSUTF8StringEncoding)!
println(jsonString)
Upvotes: 2