1

I have a dictionary of [String : Any] in which one of the value is of type array of Int. Its look something like this:

 "file_name" : "anImage.png"
 "type" : "2"
 "data_bytes" : "[-119,80,78,71,13,10,26,10,0,13,73,72,68,82,0,0,2,0,2,0,8,6,-12,120,-4]"

Now i am trying to get the value against the key data_bytes as integer array but compiler is saying that i can't cast String to Array or something other. I tried by following codes:

dictionary["data_bytes"] as? [Int]      //Failed
dictionary["data_bytes"] as? [NSNumber] //Failed
dictionary["data_bytes"] as? Array    //Failed
dictionary["data_bytes"] as? [Int8]     //Failed
dictionary["data_bytes"] as? String     //Success

I also tried looping through all characters in string:

 (dictionary["data_bytes"] as? String).flatMap( Int($0) ?? 0 ) //Failed

But its giving exception because while looping, there are characters like [ ] , that is not convertible.

How am I supposed to convert this to array of integers?

4
  • 3
    Simple JSON rule: Everything wrapped in double quotes is String, one string. Everything , there is no exception. Commented Apr 18, 2019 at 11:44
  • Possible duplicate of Convert Swift string to array Commented Apr 18, 2019 at 15:40
  • @TheNeil That's not a duplicate. Look closer. Commented Apr 19, 2019 at 5:03
  • Thanks. Flag retracted. Commented Apr 19, 2019 at 13:14

1 Answer 1

5

This is a json string

if let str =  dictionary["data_bytes"] as? String {

     do { 
         let res = try JSONDecoder().decode([Int].self,from:Data(str.utf8))
         print(res)
     }
     catch {
         print(error)
     } 

}
Sign up to request clarification or add additional context in comments.

2 Comments

@Jamil Please mark the answer accepted if it worked to help others identify the correct answer.
@Jamil, that string was valid JSON array of numbers, so it could be trivially parsed using JSONDecoder

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.