Reputation: 5829
In my swift
app I'm fetching comments from webservice. The general format of incoming json is:
comments = (
{
"_id" = 57e460a4d9f58eb150470a0a;
content = "fsagsd";
"sent_at" = "2016-09-22T22:52:20.061Z";
"username" = kamil;
},
{
"_id" = 57e460c0d9f58eb150470a0b;
content = "hfdhfd";
"sent_at" = "2016-09-22T22:52:48.682Z";
"username" = kamil;
}
);
This is an actual result of: print(response.result.value)
The whole query (with alamofire
) looks as follows:
Alamofire.request(.GET, "\(serverURL)/get/\(case_id)/comments/"/*, headers: headers*/)
.validate()
.responseJSON { response in
switch response.result {
case .Success:
print("success")
if let jsonData = response.result.value as? [[String: AnyObject]] {
for myJSON in jsonData {
if let myTest = SingleComment.fromJSON(JSON(myJSON)){
self.items.addObject(myJSON)
self.myTable.reloadData()
}
}
}
but because the comments are embedded in comments
in my json - I'm never reaching the self.items.addObject(myJSON)
. I think it would work if the incoming json looked something like:
{
"_id" = 57e460a4d9f58eb150470a0a;
content = "fsagsd";
"sent_at" = "2016-09-22T22:52:20.061Z";
"username" = kamil;
},
{
"_id" = 57e460c0d9f58eb150470a0b;
content = "hfdhfd";
"sent_at" = "2016-09-22T22:52:48.682Z";
"username" = kamil;
}
since I cannot change the incoming json - can you please help me to adjust my swift code?
One additional info - the fromJSON
function is as follows:
class func fromJSON(json: JSON) -> SingleComment? {
print("single comment from json")
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let username = json["username"].string
let content = json["content"].string
let sent_at = json["sent_at"].string
let id = json["_id"].string
let upd = dateFormatter.dateFromString(sent_at!)
return SingleComment(username: username!, content: content!, sent_at: upd!, id: id!)
}
Upvotes: 0
Views: 170
Reputation: 4579
Your response seems not to be a correct json data.
Firstly, json property should be separated by :
, not =
. In your example, "_id" = 57e460c0d9f58eb150470a0b;
should be "_id" : 57e460c0d9f58eb150470a0b;
.
Secondly, the response data seems to be a jsonp format, since is contains variable and semicolon. But the json format is still not correct. So I think you solution is not to adjust your algorithm to fit such odd "json"
data, you have to ask your server, why it provide such an odd data.
Upvotes: 0
Reputation: 5107
Try this code in .Success block. Hope it will help you.
if let value = response.result.value {
let data = JSON(value)
if let responseDictionary = data.dictionary {
if let commentsArray = responseDictionary["comments"]?.array {
for commentObject in commentsArray {
if let myTest = SingleComment.fromJSON(commentObject){
self.items.addObject(myJSON)
}
}
self.myTable.reloadData()
}
}
}
Upvotes: 1