user3766930 user3766930 - 9 days ago 6
iOS Question

what is wrong with parsing my data from json in Swift?

I'm trying to update the

UITableView
with data fetched from Alamofire.
My backend webservice returns the data as follows:

{"hashtags":["test","test2"]}


and my 'swift` code for that looks like this:

Alamofire.request("\(serverURL)/users/\(username)/hashtags")
.validate()
.responseJSON { response in
switch response.result {
case .success:
DispatchQueue.main.async(execute: {

if let jsonData = response.result.value as? [String: AnyObject] {

for hashtag in jsonData {
print(JSON(hashtag))
print(hashtag)
if let userHashtags = SingleHashtag.fromJSON(JSON(hashtag)){

for hash in userHashtags.hashtagText {
print(hash)
self.items.add(hash)


Function
SingleHashtag.fromJSON
is part of the class:

class SingleHashtag: NSObject {

var hashtagText: [String]

init(hashtagText: [String]) {
self.hashtagText = hashtagText
super.init()
}

class func fromJSON(_ json: JSON) -> SingleHashtag? {
let hashtagText:[String] = json["hashtags"].arrayValue.map { $0.stringValue}
return SingleHashtag(hashtagText: hashtagText)
}


}


and I cannot make it work. The problem is that those two lines:

print(JSON(hashtag))
print(hashtag)


print:

unknown
("hashtags", <__NSArrayI 0x170c22200>(
test,
test2
)
)


and because I'm passing
unknown
there, the rest of the code is not executed. What did I miss here?

Answer

Your JSON appears to be a dictionary who's only key contains an array of strings.

You are trying to loop through your dictinionary as if it's an array. That's wrong.

Try using 2-step optional binding like this:

if let jsonData = response.result.value as? [String: AnyObject],
      hashtags = jsonData["hashtags"] as? [String]  {
    for hashtag in hashtags {
      //your code here
    }
} 
Comments