How to codable JSON response properly by using Swift 4.2? - json

My scenario, I am trying to create codable structure for JSON response but I am getting “Type 'Datum' does not conform to protocol 'Decodable' “ error. I made some mistakes in codable but I can’t able to find it. Please check below my response and code and give me the solution.
My Response
{
"status": 200,
"message": "Success",
"country": [
{
"id": 1,
"master": "India",
"type": 2,
"active": 1
},
{
"id": 2,
"master": "US",
"type": 2,
"active": 1
}
],
"cost": 13764,
"data": [
{
"id": 1,
"user_id": 167,
"country": 1,
"card": 1,
"category": 4,
"title": “kms”,
"description": “check”,
"cost": 444,
"attachment": "sample.png",
"create_date": "2019-02-13T00:00:00.000Z",
"device_id": "1111",
"app_type": "Android",
"location": “USA”,
"user": {
"firstname": “Mike”,
"lastname": "P"
},
"app_trans_card": {
"card": “012”
},
"app_trans_master": {
"master": "Domain"
}
}
]
}
My Code
struct Root: Codable {
let status: Int
let message: String
let cost: Int
let data: [Datum]
enum CodingKeys: String, CodingKey {
case status
case message = "message"
case cost
case data
}
}
struct Datum: Codable {
let id, user_id, country, card, category, cost: Int
let title: String
let description: String
let attachment: String
let create_date: String
let device_id: String
let app_type: String
let location: String
let user: Fullname
let app_trans_card: TransactionCard
let app_trans_master: TransactionMaster
enum CodingKeys: String, CodingKey {
case id = "id"
case user_id = "user_id"
case country = "country"
case card = "card"
case category = "category"
case cost = "cost"
case title, description, attachment, create_date, device_id, app_type, location, fullname, transactionCard, transactionMaster
}
}
struct Fullname: Codable {
let firstname, lastname: String
}
struct TransactionCard: Codable {
let card: String
}
struct TransactionMaster: Codable {
let master: String
}

I have found some problem if you JSON which is related with ” at many places and it should be " so first correct that and then your JSON will be:
{
"status": 200,
"message": "Success",
"country": [
{
"id": 1,
"master": "India",
"type": 2,
"active": 1
},
{
"id": 2,
"master": "US",
"type": 2,
"active": 1
}
],
"cost": 13764,
"data": [
{
"id": 1,
"user_id": 167,
"country": 1,
"card": 1,
"category": 4,
"title": "kms",
"description": "check",
"cost": 444,
"attachment": "sample.png",
"create_date": "2019-02-13T00:00:00.000Z",
"device_id": "1111",
"app_type": "Android",
"location": "USA",
"user": {
"firstname": "Mike",
"lastname": "P"
},
"app_trans_card": {
"card": "012"
},
"app_trans_master": {
"master": "Domain"
}
}
]
}
Now you can create your Codable protocol with THIS site and code it will look like:
struct Root: Codable {
let status: Int
let message: String
let country: [Country]
let cost: Double
let data: [Datum]
}
struct Country: Codable {
let id: Int
let master: String
let type, active: Int
}
struct Datum: Codable {
let id, userID, country, card: Int
let category: Int
let title, description: String
let cost: Double
let attachment, createDate, deviceID, appType: String
let location: String
let user: User
let appTransCard: AppTransCard
let appTransMaster: AppTransMaster
enum CodingKeys: String, CodingKey {
case id
case userID = "user_id"
case country, card, category, title, description, cost, attachment
case createDate = "create_date"
case deviceID = "device_id"
case appType = "app_type"
case location, user
case appTransCard = "app_trans_card"
case appTransMaster = "app_trans_master"
}
}
struct AppTransCard: Codable {
let card: String
}
struct AppTransMaster: Codable {
let master: String
}
struct User: Codable {
let firstname, lastname: String
}

Related

Stuck Decoding Multidimensional JSON From URLSession

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

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)
}

Type 'AreaData' does not conform to protocol 'Encodable'

When I make a model for my JSON file, I get these two errors.
1) I got the conform error in AreaData struct
2) "AnyObject cannot be used as a type conforming to protocol Decodable because Decodable has static requirements" error in initialiser.
I have tried several ways but I cannot find the correct solution. How can I make a proper model for this nested/complex JSON?
Here is my JSON file. This data is nested
[
{
"ID": "01",
"Name": "Area 01",
"parentId": null,
"sublevel": [
{
"ID": "01-01",
"Name": "Building 01",
"On": "",
"Off": "",
"parentId": "01",
"sublevel": [
{
"ID": "01-01-01",
"Name": "Flat 01",
"On": "",
"Off": "",
"parentId": "01-01",
"sublevel": []
}
]
},
{
"ID": "01-02",
"Name": "Building 02",
"On": "01",
"Off": "03",
"parentId": "01",
"sublevel": [
{
"ID": "01-02-01",
"Name": "Flat 01",
"On": "",
"Off": "",
"parentId": "01-02",
"sublevel": []
},
{
"ID": "01-02-02",
"Name": "Flat 02",
"On": "01",
"Off": "02",
"parentId": "01-02",
"sublevel": []
},
{
"ID": "01-02-03",
"Name": "Flat 03",
"On": "02",
"Off": "12",
"parentId": "01-02",
"sublevel": [
{
"ID": "01-02-03-01",
"Name": "Room 01",
"On": "",
"Off": "",
"parentId": "01-02-03",
"sublevel": []
},
{
"ID": "01-02-03-02",
"Name": "Room 02",
"On": "",
"Off": "",
"parentId": "01-02-03",
"sublevel": []
},
{
"ID": "01-02-03-03",
"Name": "Room 03",
"On": "02",
"Off": "03",
"parentId": "01-02-03",
"sublevel": []
},
{
"ID": "01-02-03-04",
"Name": "Room 04",
"On": "",
"Off": "",
"parentId": "01-02-03",
"sublevel": []
},
{
"ID": "01-02-03-05",
"Name": "Room 05",
"On": "01",
"Off": "",
"parentId": "01-02-03",
"sublevel": []
}
]
},
{
"ID": "01-02-04",
"Name": "Flat 04",
"On": "12",
"Off": "03",
"parentId": "01-02",
"sublevel": []
},
{
"ID": "01-02-05",
"Name": "Flat 05",
"On": "02",
"Off": "",
"parentId": "01-02",
"sublevel": []
}
]
},
{
"ID": "01-03",
"Name": "Building 03",
"On": "02",
"Off": "01",
"parentId": "01",
"sublevel": []
},
{
"ID": "01-04",
"Name": "Building 04",
"On": "",
"Off": "",
"parentId": "01",
"sublevel": []
}
]
}
]
And this is my model class
import Foundation
struct AreaData : Codable {
let iD : String?
let name : String?
let parentId : AnyObject?
let sublevel : [Sublevel]?
enum CodingKeys: String, CodingKey {
case iD = "ID"
case name = "Name"
case parentId = "parentId"
case sublevel = "sublevel"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
iD = try values.decodeIfPresent(String.self, forKey: .iD)
name = try values.decodeIfPresent(String.self, forKey: .name)
parentId = try values.decodeIfPresent(AnyObject.self, forKey: .parentId)
sublevel = try values.decodeIfPresent([Sublevel].self, forKey: .sublevel)
}
}
struct Sublevel : Codable {
let on : String?
let iD : String?
let name : String?
let off : String?
let parentId : String?
let sublevel : [Sublevel]?
enum CodingKeys: String, CodingKey {
case on = "On"
case iD = "ID"
case name = "Name"
case off = "Off"
case parentId = "parentId"
case sublevel = "sublevel"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
on = try values.decodeIfPresent(String.self, forKey: .on)
iD = try values.decodeIfPresent(String.self, forKey: .iD)
name = try values.decodeIfPresent(String.self, forKey: .name)
off = try values.decodeIfPresent(String.self, forKey: .off)
parentId = try values.decodeIfPresent(String.self, forKey: .parentId)
sublevel = try values.decodeIfPresent([Sublevel].self, forKey: .sublevel)
}
}
try this,
struct AreaDataModel: Codable {
let id, name: String
let parentID: String? // AnyObject can't conform to Encodable protocol .
let sublevel: [Sublevel]
enum CodingKeys: String, CodingKey {
case id = "ID"
case name = "Name"
case parentID = "parentId"
case sublevel
}
}
// MARK: - Sublevel
struct Sublevel: Codable {
let id, name, on, off: String
let parentID: String
let sublevel: [Sublevel]
enum CodingKeys: String, CodingKey {
case id = "ID"
case name = "Name"
case on = "On"
case off = "Off"
case parentID = "parentId"
case sublevel
}
}
typealias AreaData = [AreaDataModel]
I recommend this tool simple and fast .
The problem is due to AnyObject. Codabe doesn't support anything like Any or AnyObject. You need to specify the type explicitly.
In the JSON response you added, the parentId is either null or String. So, you can use String? as its type, i.e
struct AreaData : Codable {
let parentId : String? //here.....
//rest of the code....
}
Also, there is no need to specify the rawValue of the case explitly in enum CodingKeys if the property and the key has an exact match. So the CodingKeys in struct AreaData must be,
enum CodingKeys: String, CodingKey {
case iD = "ID"
case name = "Name"
case parentId, sublevel
}
Moreover, init(from decoder: Decoder) is not required. This is because you're not doing any specific parsing inside it. Direct parsing will be handled by the Codable itself.
So, struct AreaData should look like,
struct AreaData : Codable {
let iD : String?
let name : String?
let parentId : String?
let sublevel : [Sublevel]?
enum CodingKeys: String, CodingKey {
case iD = "ID"
case name = "Name"
case parentId, sublevel
}
}
Make similar changes to struct Sublevel as well.
Also, use Codable only if you want to both encode and decode the data. In case you want a single functionality i.e. either encode or decode, use Encodable or Decodable instead.
Recommendation:
Since the AreaData and Sublevel contain almost same kind of data, you can use a single struct to decode that JSON, i.e.
struct AreaData: Decodable {
let iD : String?
let name : String?
let parentId : String?
let sublevel : [AreaData]?
let on : String?
let off : String?
enum CodingKeys: String, CodingKey {
case iD = "ID"
case name = "Name"
case on = "On"
case off = "Off"
case parentId, sublevel
}
}

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.