Stuck Decoding Multidimensional JSON From URLSession - json

I have been stuck for a few days trying to decode a multidimensional JSON array from a URLSession call. This is my first project decoding JSON in SwiftUI. My attempts from reading up on methods others suggest do not seem to work.
Here is my JSON response from the server
"success": true,
"message": "Authorized",
"treeData": {
"Right": {
"G1P1": {
"Name": "John Johnson",
"ID": 387,
"SubText": "USA 2002"
},
"G2P1": {
"Name": "Tammy Johnson",
"ID": 388,
"SubText": "USA 2002"
},
"G2P2": {
"Name": "Susan Johnson",
"ID": 389,
"SubText": "USA 1955"
}
},
"Left": {
"G1P1": {
"Name": "Jane Doe",
"ID": 397,
"SubText": "USA 2002"
},
"G2P1": {
"Name": "John Doe",
"ID": 31463,
"SubText": "USA 2002"
},
"G2P2": {
"Name": "Susan Doe",
"ID": 29106,
"SubText": "USA 1958"
}
}
}
}
Here is my decode block of code
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data, error == nil else {
completion(.failure(.noData))
return
}
guard let treeResponse = try? JSONDecoder().decode([String: TreeResponse].self, from: data) else {
completion(.failure(.decodingError))
return
}
dump(treeResponse)
completion(.success("Hooray"))
}.resume()
And then here are my structs, which is the part I can't seem to figure out
struct TreeResponse: Codable {
let success: Bool
let message: String
let treeData: [String:SideData]
}
struct SideData: Codable {
let personKey: [String:PersonInfo]
}
struct PersonInfo: Codable {
let Name: String
let ID: Int
let SubText: String
}
My hope is to be able to access the decoded data as treeResponse.Right.G1P1.Name
Could really use help moving past this

I will post this as an answer even if it cannot be one, but that way I can at least format it properly :-).
First of all you should learn to pose your questions in a manner that makes it as easy as possible for anyone to execute your code. Swift has a particularly helpful way of doing this, you can run a Playground on it. Then you should start whittling down your question to its essence which appears to be the JSON decode. JSONDecoder usually is very helpful in providing you with decent error messages on what it does not like about your JSON, but you have to print them. A suitable Playground would look as follows:
import UIKit
let jsonStr = """
{
"success": true,
"message": "Authorized",
"treeData": {
"Right": {
"G1P1": {
"Name": "John Johnson",
"ID": 387,
"SubText": "USA 2002"
},
"G2P1": {
"Name": "Tammy Johnson",
"ID": 388,
"SubText": "USA 2002"
},
"G2P2": {
"Name": "Susan Johnson",
"ID": 389,
"SubText": "USA 1955"
}
},
"Left": {
"G1P1": {
"Name": "Jane Doe",
"ID": 397,
"SubText": "USA 2002"
},
"G2P1": {
"Name": "John Doe",
"ID": 31463,
"SubText": "USA 2002"
},
"G2P2": {
"Name": "Susan Doe",
"ID": 29106,
"SubText": "USA 1958"
}
}
}
}
"""
struct TreeResponse: Codable {
let success: Bool
let message: String
let treeData: [String:SideData]
}
struct SideData: Codable {
let personKey: [String:PersonInfo]
}
struct PersonInfo: Codable {
let Name: String
let ID: Int
let SubText: String
}
let jsonData = jsonStr.data(using:.utf8)!
do {
let tree = try JSONDecoder().decode(TreeResponse.self, from: jsonData)
print(tree)
} catch {
print(tree)
}
This will yield a somewhat descriptive error message:
keyNotFound(CodingKeys(stringValue: "personKey", intValue: nil),
Swift.DecodingError.Context(codingPath:
[CodingKeys(stringValue: "treeData", intValue: nil),
_JSONKey(stringValue: "Right", intValue: nil)],
debugDescription: "No value associated with key
CodingKeys(stringValue: \"personKey\", intValue: nil)
(\"personKey\").", underlyingError: nil))
(Indentation mine and not particularly well thought out)
This starts pointing out your problems (of which you still seem to have a lot).
The first level of decode is somewhat ok, but the second level is woefully inadequate in its current form. There is no such thing as a personKey in your JSON which would be required to fit it into a simple struct. However you still might be able to coax it through some decode method.
Considering you JSON that appears to be a bad choice and you should opt for properly modelling your tree with the given Left and Right keys, although this is probably scratching the limit of what Decodable will do for you for free, so you will have to put in some more work to get this to work on a more involved example. If the keys on the following levels have any special significance you will have to put in a special decode there too.
In any way, you should definitely learn to formulate your questions better.

when our structure are not perfect to JSON so that's why get this types error and i've use JSONDecoder to retrieve the data from JSON couldn't read the data it's missing, though, such error yet get so needs to create quite perfect JSON models or create model with CodingKeys such like:
struct JSONData: Codable {
let success: Bool
let message: String
let treeData: TreeData
}
struct TreeData: Codable {
let treeDataRight, treeDataLeft: [String: Left]
enum CodingKeys: String, CodingKey {
case treeDataRight = "Right"
case treeDataLeft = "Left"
}
}
struct Left: Codable {
let name: String
let id: Int
let subText: String
enum CodingKeys: String, CodingKey {
case name = "Name"
case id = "ID"
case subText = "SubText"
}
}
For get JSON data to need JSONDecoder():
let jsonData = jsonStr.data(using:.utf8)!
do {
let tree = try JSONDecoder().decode(JSONData.self, from: jsonData)
dump(tree)
} catch {
print(error.localizedDescription)
}
Together with json, JSON model, JSONDecoder():
let jsonStr = """
{
"success": true,
"message": "Authorized",
"treeData": {
"Right": {
"G1P1": {
"Name": "John Johnson",
"ID": 387,
"SubText": "USA 2002"
},
"G2P1": {
"Name": "Tammy Johnson",
"ID": 388,
"SubText": "USA 2002"
},
"G2P2": {
"Name": "Susan Johnson",
"ID": 389,
"SubText": "USA 1955"
}
},
"Left": {
"G1P1": {
"Name": "Jane Doe",
"ID": 397,
"SubText": "USA 2002"
},
"G2P1": {
"Name": "John Doe",
"ID": 31463,
"SubText": "USA 2002"
},
"G2P2": {
"Name": "Susan Doe",
"ID": 29106,
"SubText": "USA 1958"
}
}
}
}
"""
struct JSONData: Codable {
let success: Bool
let message: String
let treeData: TreeData
}
struct TreeData: Codable {
let treeDataRight, treeDataLeft: [String: Left]
enum CodingKeys: String, CodingKey {
case treeDataRight = "Right"
case treeDataLeft = "Left"
}
}
struct Left: Codable {
let name: String
let id: Int
let subText: String
enum CodingKeys: String, CodingKey {
case name = "Name"
case id = "ID"
case subText = "SubText"
}
}
let jsonData = jsonStr.data(using:.utf8)!
do {
let tree = try JSONDecoder().decode(JSONData.self, from: jsonData)
dump(tree)
} catch {
print(error.localizedDescription)
}
Result:
Result here
and i hope this would work and helpfully so try once

Related

How to parse this type of data to a JSON in Swift?

I have called an API to get all holidays in a year, it came out a Json type. But I only can extract it like below (it is one of many elements of "items")
"items": [
{
"kind": "calendar#event",
"etag": "\"3235567993214000\"",
"id": "20200101_1814eggq09ims8ge9pine82pclgn49rj41262u9a00oe83po05002i01",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=MjAyMDAxMDFfMTgxNGVnZ3EwOWltczhnZTlwaW5lODJwY2xnbjQ5cmo0MTI2MnU5YTAwb2U4M3BvMDUwMDJpMDEgZW4udWsjaG9saWRheUB2",
"created": "2021-04-07T08:26:36.000Z",
"updated": "2021-04-07T08:26:36.607Z",
"summary": "New Year's Day",
"creator": {
"email": "en.uk#holiday#group.v.calendar.google.com",
"displayName": "Holidays in United Kingdom",
"self": true
},
"organizer": {
"email": "en.uk#holiday#group.v.calendar.google.com",
"displayName": "Holidays in United Kingdom",
"self": true
},
"start": {
"date": "2020-01-01"
},
"end": {
"date": "2020-01-02"
},
"transparency": "transparent",
"visibility": "public",
"iCalUID": "20200101_1814eggq09ims8ge9pine82pclgn49rj41262u9a00oe83po05002i01#google.com",
"sequence": 0,
"eventType": "default"
},
{
"kind": "calendar#event",
"etag": "\"3235567993214000\"",
"id": "20200412_1814eggq09ims8gd8lgn6t35e8g56tbechgniag063i0ue048064g0g",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=MjAyMDA0MTJfMTgxNGVnZ3EwOWltczhnZDhsZ242dDM1ZThnNTZ0YmVjaGduaWFnMDYzaTB1ZTA0ODA2NGcwZyBlbi51ayNob2xpZGF5QHY",
"created": "2021-04-07T08:26:36.000Z",
"updated": "2021-04-07T08:26:36.607Z",
"summary": "Easter Sunday",
"creator": {
"email": "en.uk#holiday#group.v.calendar.google.com",
"displayName": "Holidays in United Kingdom",
"self": true
},
"organizer": {
"email": "en.uk#holiday#group.v.calendar.google.com",
"displayName": "Holidays in United Kingdom",
"self": true
},
"start": {
"date": "2020-04-12"
},
"end": {
"date": "2020-04-13"
},
"transparency": "transparent",
"visibility": "public",
"iCalUID": "20200412_1814eggq09ims8gd8lgn6t35e8g56tbechgniag063i0ue048064g0g#google.com",
"sequence": 0,
"eventType": "default"
}
I try to get the value in key "start" and key "summary" but I can't.
Xcode told me that "items" is a __NSArrayI type.
What I've tried so far is create a class simple like this (just use to try first, so I didn't make all variable)
class API_Info {
var kind: String?
var etag: String?
var id: String?
var status: String?
var htmlLink: String?
var created: String?
var updated: String?
var summary: String?
init(items: [String:Any]){
self.kind = items["kind"] as? String
self.etag = items["etag"] as? String
self.id = items["id"] as? String
self.status = items["status"] as? String
self.htmlLink = items["htmlLink"] as? String
self.created = items["created"] as? String
self.updated = items["updated"] as? String
self.summary = items["summary"] as? String
}
}
And I parse like this:
guard let items = json!["items"]! as? [API_Info] else{
print("null")
return
}
In this way, else statement was run.
What am I doing wrong, and how can I get the data I want?
Thanks in advance.
Codable is the solution here. Below is the struct I used rather than your class
struct ApiInfo: Codable {
let kind: String
let etag: String
let id: String
let status: String
let htmlLink: String
let created: Date
let updated: Date
let summary: String
}
Then I created a root type to hold the array
struct Result: Codable {
let items: [ApiInfo]
}
And then the decoding
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
do {
let result = try decoder.decode(Result.self, from: data)
print(result.items)
} catch {
print(error)
}
Notice that the data values are decoded to Date objects.
Optionally you can skip the root type and decode as a dictionary
do {
let items = try decoder.decode([String: [ApiInfo]].self, from: data)
if let values = items["items"] {
print(values)
}
} catch {
print(error)
}

How to parse local JSON data in Swift?

How to parse local JSON data where nested (optional) property is same as main.
Items data may be available or may not be available.
struct Category: Identifiable, Codable {
let id: Int
let name: String
let image: String
var items: [Category]?
}
I am using common Bundle extension to parse JSON data.
extension Bundle {
func decode<T: Codable>(_ file: String) -> T {
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate \(file) in bundle.")
}
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load \(file) from bundle.")
}
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.dateFormat = "y-MM-dd"
decoder.dateDecodingStrategy = .formatted(formatter)
guard let loaded = try? decoder.decode(T.self, from: data) else {
fatalError("Failed to decode \(file) from bundle.")
}
return loaded
}
}
For eg data :
[
{
"id": 1,
"name": "Apple",
"image": "img_url",
"items" : [
{
"id": 1,
"name": "iPhone",
"image": "img_url",
"items" : [
{
"id": 1,
"name": "iPhone 11 Pro",
"image": "img_url"
},
{
"id": 2,
"name": "iPhone 11 Pro Max",
"image": "img_url"
}
]
},
{
"id": 2,
"name": "iPad",
"image": "img_url",
"items" : [
{
"id": 1,
"name": "iPad mini",
"image": "img_url"
},
{
"id": 2,
"name": "iPad Air",
"image": "img_url"
},
{
"id": 3,
"name": "iPad Pro",
"image": "img_url"
}
]
}
]
},
{
"id": 2,
"name": "Samsung",
"image": "img_url",
"items" : [
{
"id": 1,
"name": "Phone",
"image": "img_url"
},
{
"id": 2,
"name": "Tablet",
"image": "img_url"
}
]
}
]
Nesting is not the issue here, You are facing an Array of Contents. so you should pass [Content] to the decoder like:
let jsonDecoder = JSONDecoder()
try! jsonDecoder.decode([Category].self, from: json)
🎁 Property Wrapper
You can implement a simple property wrapper for loading and decoding all of your properties:
#propertyWrapper struct BundleFile<DataType: Decodable> {
let name: String
let type: String = "json"
let fileManager: FileManager = .default
let bundle: Bundle = .main
let decoder = JSONDecoder()
var wrappedValue: DataType {
guard let path = bundle.path(forResource: name, ofType: type) else { fatalError("Resource not found") }
guard let data = fileManager.contents(atPath: path) else { fatalError("File not loaded") }
return try! decoder.decode(DataType.self, from: data)
}
}
Now you can have any property that should be loaded from a file in a Bundle like:
#BundleFile(name: "MyFile")
var contents: [Content]
Note that since the property should be loaded from the bundle, I raised a FatalError. Because the only person should be responsible for these errors is the developer at the code time (not the run time).

Parsing local json file on Swift

I have a local JSON and try to decode but got "Expected to decode Array but found a dictionary instead" error. The json file and two structs below:
{
"Stanford University": [{
"type": "government",
"name": "Stanford University",
"city": "Santa Clara",
"major": "Computer Engineering"
},
{
"type": "government",
"name": "Stanford University",
"city": "Santa Clara",
"major": "Economics"
}
],
"Berkeley University": [{
"type": "foundation",
"name": "Berkeley University",
"city": "Alameda",
"major": "Communication"
},
{
"type": "foundation",
"name": "Berkeley University",
"city": "Alameda",
"major": "Physics"
}
]
}
two structs:
struct Universite4: Codable {
let name: String?
let major:[Major]?
}
struct Major: Codable {
let type: String?
let name: String?
let major: String? }
And this is code for data load and decode;
public class DataLoader {
#Published var universite4 = [Universite4]()
init() {
load()
}
func load() {
if let unv4json = Bundle.main.url(forResource: "unv4", withExtension: "json") {
do {
let data = try Data(contentsOf: unv4json)
let jsonDecoder = JSONDecoder()
let dataFromJson = try jsonDecoder.decode([Universite4].self, from:data)
self.universite4 = dataFromJson
} catch {
print("Error: \(error)")
}
}
}
}
Does anybody know how can I fix above code? Regards.
Try to change, the issue here is that actually your keys are sort of "Dynamic keys" which I don't recommend but if you have to use them, so try this.
let dataFromJson = try jsonDecoder.decode([Universite4].self, from:data)
to
let dataFromJson = try jsonDecoder.decode([String:[Major]].self, from:data)

Parse data using Alamofire and SwiftyJson

My JSON -
"documents": {
"driver": [
{
"id": 1,
"name": "Driving Licence",
"type": "DRIVER",
"provider_document": {
"id": 9,
"provider_id": 165,
"document_id": "1",
"url": "https://boucompany.com/storage/provider/documents/b92cf551a62b6b8c183997b41b9543c6.jpeg",
"unique_id": null,
"status": "ACTIVE",
"expires_at": null,
"created_at": "2019-04-26 19:05:58",
"updated_at": "2019-04-27 06:37:56"
}
},
{
"id": 2,
"name": "Bank Passbook",
"type": "DRIVER",
"provider_document": null
},
{
"id": 3,
"name": "Joining Form",
"type": "DRIVER",
"provider_document": null
},
{
"id": 4,
"name": "Work Permit",
"type": "DRIVER",
"provider_document": null
},
{
"id": 8,
"name": "Test Document",
"type": "DRIVER",
"provider_document": null
},
{
"id": 9,
"name": "NID Card",
"type": "DRIVER",
"provider_document": null
},
{
"id": 10,
"name": "Matrícula",
"type": "DRIVER",
"provider_document": null
}
],
I want to parse the url name.I have used Alamofire and SwiftyJson in my project. So far i have tried -
self.documentsDriver = json["documents"]["driver"][0]["provider_document"]["url"].stringValue
How can i print the value or "url" using swiftyjson
You can use Encodable to parse this response as below,
struct Response: Codable {
let documents: Documents
}
struct Documents: Codable {
let driver: [Driver]
}
struct Driver: Codable {
let id: Int
let name, type: String
let providerDocument: ProviderDocument?
enum CodingKeys: String, CodingKey {
case id, name, type
case providerDocument = "provider_document"
}
}
struct ProviderDocument: Codable {
let id, providerID: Int
let documentID: String
let url: String
let status: String
let createdAt, updatedAt: String
enum CodingKeys: String, CodingKey {
case id
case providerID = "provider_id"
case documentID = "document_id"
case url
case status
case createdAt = "created_at"
case updatedAt = "updated_at"
}
}
To parse the response,
let jsonData = Data() // Your API response data.
let response = try? JSONDecoder().decode(Response.self, from: jsonData)
response.documents.driver.forEach { driver in
print(driver.providerDocument?.url)
}
Parse JSON data using SwiftyJSON
func convertJSONToDriverModel(json: JSON) {
if let driver = json["documents"]["driver"].array {
for driverJson in driver {
let driverObj = convertToDriverJSONModel(json: driverJson)
print(driverObj)
}
}
}
func convertToDriverJSONModel(json: JSON) {
let name = json["name"].string ?? ""
if let providerDetails = json["provider_document"].dictionary {
let url = convertToProductDetailsJSONModel(json: JSON(providerDetails))
print("URL is: \(url)")
}
}
// Method to parse data inside provider_document (Here I have parsed only url)
func convertToProviderDocumentJSONModel(json: JSON) -> String {
let url = json["url"].string ?? ""
return url
}

How to parse complex JSON in Swift 4 using Codable

I need help with parsing JSON from server. Here's the JSON:
{
"response": {
"items": [
{
"type": "post",
"source_id": -17507435,
"date": 1514538602,
"post_id": 4105,
"post_type": "post",
"text": "Some text here",
"marked_as_ads": 0,
"attachments": [
{
"type": "photo",
"photo": {
"id": 456239655,
"album_id": -7,
"owner_id": -17507435,
"user_id": 100,
"photo_75": "https://sun1-3.userapi.com/c840632/v840632924/3b7e7/4YUS7DlaLK8.jpg",
"photo_130": "https://sun1-3.userapi.com/c840632/v840632924/3b7e8/Ffpb4ZUlulI.jpg",
"photo_604": "https://sun1-3.userapi.com/c840632/v840632924/3b7e9/-pkl6Qdb9hk.jpg",
"width": 439,
"height": 312,
"text": "",
"date": 1514538602,
"post_id": 4105,
"access_key": "6a61a49570efd9c39c"
}
}
],
"post_source": {
"type": "api"
},
"comments": {
"count": 0,
"groups_can_post": true,
"can_post": 1
},
"likes": {
"count": 0,
"user_likes": 0,
"can_like": 1,
"can_publish": 1
},
"reposts": {
"count": 0,
"user_reposted": 0
},
"views": {
"count": 2
}
}
],
"profiles": [],
"groups": [
{
"id": 17507435,
"name": "Literature Museum",
"screen_name": "samlitmus",
"is_closed": 0,
"type": "group",
"is_admin": 0,
"is_member": 1,
"photo_50": "https://pp.userapi.com/c615722/v615722068/e58c/d5Y8E_5689s.jpg",
"photo_100": "https://pp.userapi.com/c615722/v615722068/e58b/Hm05ga3x2J8.jpg",
"photo_200": "https://pp.userapi.com/c615722/v615722068/e589/yoG_DDalFII.jpg"
},
{
"id": 27711883,
"name": "E:\\music\\melodic hardcore",
"screen_name": "e_melodic_hc",
"is_closed": 0,
"type": "page",
"is_admin": 0,
"is_member": 1,
"photo_50": "https://pp.userapi.com/c628220/v628220426/47092/xepNnC7pSBw.jpg",
"photo_100": "https://pp.userapi.com/c628220/v628220426/47091/uAokr-c3NQ8.jpg",
"photo_200": "https://pp.userapi.com/c628220/v628220426/4708f/eNY4vzooz4E.jpg"
},
{
"id": 81574241,
"name": "DOS4GW.EXE",
"screen_name": "dos4gw",
"is_closed": 0,
"type": "page",
"is_admin": 0,
"is_member": 1,
"photo_50": "https://pp.userapi.com/c622118/v622118651/e045/vlhV6QxtoLI.jpg",
"photo_100": "https://pp.userapi.com/c622118/v622118651/e044/P9mVUhXBV58.jpg",
"photo_200": "https://pp.userapi.com/c622118/v622118651/e043/Soq8oxCMB0I.jpg"
},
{
"id": 76709587,
"name": "Prosvet",
"screen_name": "prosvet_pub",
"is_closed": 0,
"type": "page",
"is_admin": 0,
"is_member": 0,
"photo_50": "https://pp.userapi.com/c630431/v630431500/b24a/GHox8AmDTXU.jpg",
"photo_100": "https://pp.userapi.com/c630431/v630431500/b249/H3mcC-K7htM.jpg",
"photo_200": "https://pp.userapi.com/c630431/v630431500/b248/9fyvB8gkcwc.jpg"
}
],
"next_from": "1/4105_1514494800_5"
}
}
What I need to get from this JSON are lines: "text", "comments", "likes", "reposts", "attachments".
Inside "attachments" field I want to get "photo_604" line.
Here's my code:
class NewsItems: Decodable {
var text: String?
var comments: Comments
var likes: Likes
var reposts: Reposts
var attachments: [Attachments]
}
class Comments: Decodable {
var count: Int?
}
class Likes: Decodable {
var count: Int?
}
class Reposts: Decodable {
var count: Int?
}
class Attachments: Decodable {
var attachments: AttachmentPhoto
}
class AttachmentPhoto: Decodable {
var photo: WhatIsInsideAttachmentsPhoto
}
class WhatIsInsideAttachmentsPhoto: Decodable {
var photo: String?
enum CodingKeys: String, CodingKey {
case photo = "photo_604"
}
}
class WhatIsIsideResponseNewsFeed: Decodable {
var items: [NewsItems]
}
public class ResponseNewsFeed: Decodable {
var response: WhatIsIsideResponseNewsFeed
}
But after making the request:
Alamofire.request(baseURL+methodName, parameters: parameters).responseData(completionHandler: { response in
if let result = response.result.value {
let decoder = JSONDecoder()
let myResponse = try! decoder.decode(ResponseNewsFeed.self, from: result)
completion(myResponse.response.items)
I get an error:
Fatal error: 'try!' expression unexpectedly raised an error:
Swift.DecodingError.keyNotFound(_UL_PetrovLeonid.NewsItems.(CodingKeys
in _FA9A2FC8130449AA328C19ACD9506C2D).attachments,
Swift.DecodingError.Context(codingPath:
[_UL_Leonid.ResponseNewsFeed.(CodingKeys in
_FA9A2FC8130449AA328C19ACD9506C2D).response, _UL_PetrovLeonid.WhatIsIsideResponseNewsFeed.(CodingKeys in _FA9A2FC8130449AA328C19ACD9506C2D).items, Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 0", intValue: Optional(0))], debugDescription: "No value associated with key
attachments (\"attachments\").", underlyingError: nil))
Why is that happening and what do I need to do to solve it? I've been into coding only three months from now, so please forgive me beforehand if my problem seems silly.
Thank you.
The error message is very clear
... Swift.DecodingError.keyNotFound ... NewsItems.(CodingKeys in _FA9A2FC8130449AA328C19ACD9506C2D).attachments ... No value associated with key attachments (\"attachments\").
keyNotFound is key is missing
NewsItems.(CodingKeys ... ).attachments is the object for key attachments in NewsItems which is Attachments
No value associated with key attachments (\"attachments\") is what is says.
Shortly: There is no key attachments in Attachments which is true.
Look at your JSON
"attachments": [
{
"type": "photo",
"photo": {
The class equivalent is
class Attachments: Decodable {
let type : String
let photo : AttachmentPhoto
}
And AttachmentPhoto is supposed to be
class AttachmentPhoto: Decodable {
private enum CodingKeys : String, CodingKey {
case photo604 = "photo_604"
case id
}
let id : Int
let photo604 : String // or even URL
// etc.
}
Actually there is no need to use classes, in most cases a struct is sufficient.