Search code examples
arraysjsonswiftnsjsonserializationjsonserializer

How can I serialize Array of JSON with arrays from a file in path?


I have a .json file into my Xcode project using Swift. I need load the content and parse to use in my controller, butn when I try serialize the file content to an jsonObject I'm getting errors parsing...

I have read another similar questions but I haven't found a similar Array of JSON to read with different structures contained and another Array of JSON into the object.

The format of array JSON is:

[
  {
    "title": "The App",
    "description": "This is the description",
    "friends": [
      {
        "name": "Gary",
        "image": "http://",
        "description": "Nice"
      },
      {
        "name": "Patri",
        "image": "http://",
        "description": "Amazing"
      },
      {
        "name": "Lucy",
        "image": "http://",
        "description": "Up"
      }
    ]
  }
]

I'm using this code to get the content of file from bundle path(data.json added to my proyect) and then serialize, but always get an error because Friends contains an array of json.

let path = Bundle.main.path(forResource: "data", ofType: "json")
let jsonData = try! Data(contentsOf: URL(fileURLWithPath: path!))
let jsonResult = try! JSONSerialization.jsonObject(with: jsonData, options: []) as? [[String:Any]] //Here is the error parsing the array of Friend of JSON

How can I parse this array of json that contains another array of jsonObjects?


Solution

  • You need to use Codable

    // MARK: - Element
    struct Root: Codable {
        let title, purpleDescription: String
        let friends: [Friend]
    
        enum CodingKeys: String, CodingKey {
            case title
            case purpleDescription = "description"
            case friends
        }
    }
    
    // MARK: - Friend
    struct Friend: Codable {
        let name, image, friendDescription: String
    
        enum CodingKeys: String, CodingKey {
            case name, image
            case friendDescription = "description"
        }
    }
    

    let url = Bundle.main.url(forResource: "data", withExtension: "json")
    let jsonData = try! Data(contentsOf:url)
    let res = try! JSONDecoder().decode([Root].self,from:data)
    print(res)