Search code examples
iosjsonswift

Convert String to [[String]]


I work with [[String]] to populate my collection view Cells.

I fetch this data with API:

{
  identifier: {
    channel: "WorldChannel",
    id: 1
  },
  message: {
    map: "[[null,null,\"penguin\",null,\"penguin\",null,null],[null,\"penguin\",\"penguin\",\"penguin\",\"orca...ll,null,\"penguin\",null,null,null],[\"penguin\",\"penguin\",\"penguin\",null,null,null,null,null]]"
  }
}

To fetch map value I use:

struct ResponseData: Codable {
    let message: Message
}
struct Message: Codable {
    let map: String
}

I tried working with map as [[String]] but decoding gave me the following error:
CodingKeys(stringValue: "map", intValue: nil)], debugDescription: "Expected to decode Array but found a string/data instead." Which seems to be fair as map value is wrapped in " " even though what's inside is clearly a 2-D array.
Decoding part:

let jsonData = string.data(using: .utf8)!
let responseData = try! JSONDecoder().decode(ResponseData.self, from: jsonData)
mapAsString = responseData.message.map

print(maAsString!) results in:

[[null,"penguin","orca",...],...,[..."penguin",null,null]]

What I want to do is something like mapAs2DArray = mapAsString as! [[String]] but Xcode says it always fails. How can I change the data type? How can i replace null with nil or any other value to operate with?


Solution

  • You need to convert the json string to array

     let data = Data(responseData.message.map.utf8)
     let arr = try JSONDecoder().decode([[String?]].self,from:data)
     let filtered  = arr.map { $0.compactMap{ $0 } } // remove null values