I am trying to parse json data in decodable in swift 4. It prints nil value. i could not find what issue is this?
here is model class:
public struct TaskID: Decodable {
let embedded: Embedded?
let count: Int?
enum CodingKeys: String, CodingKey {
case count = "count"
case embedded = "_embedded"
}
}
public struct Embedded: Decodable {
let task: [Task]?
enum CodingKeys: String, CodingKey {
case task = "task"
}
}
public struct Task : Decodable {
let id : String?
let name: String?
let assignee: String?
let created: String?
let processDefinitionId: String?
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
case assignee = "assignee"
case created = "created"
case processDefinitionId = "processDefinitionId"
}
}
Here is json:
{
"_links": {
"self": {
"href": "/task"
}
},
"_embedded": {
"task": [
{
"_links": {
"assignee": {
"href": "/user/demo"
},
"execution": {
"href": "/execution/1b64cf75-0616-11ea-8860-120ef5ab2c25"
},
"identityLink": {
"href": "/task/1b64f688-0616-11ea-8860-120ef5ab2c25/identity-links"
},
"processDefinition": {
"href": "/process-definition/quickEvaluation:1:129ce2b1-0616-11ea-8860-120ef5ab2c25"
},
"processInstance": {
"href": "/process-instance/1b64cf75-0616-11ea-8860-120ef5ab2c25"
},
"self": {
"href": "/task/1b64f688-0616-11ea-8860-120ef5ab2c25"
}
},
"_embedded": {
"variable": []
},
"id": "1b64f688-0616-11ea-8860-120ef5ab2c25",
"name": "Quick Evaluation",
"assignee": "demo",
"created": "2019-11-13T13:04:20.687+0000",
"due": null,
"followUp": null,
"delegationState": null,
"description": null,
"executionId": "1b64cf75-0616-11ea-8860-120ef5ab2c25",
"owner": null,
"parentTaskId": null,
"priority": 50,
"processDefinitionId": "quickEvaluation:1:129ce2b1-0616-11ea-8860-120ef5ab2c25",
"processInstanceId": "1b64cf75-0616-11ea-8860-120ef5ab2c25",
"taskDefinitionKey": "QuickEvaluation",
"caseExecutionId": null,
"caseInstanceId": null,
"caseDefinitionId": null,
"suspended": false,
"formKey": "a8apps:suryoday:gng:v0.1.0:kycUpload",
"tenantId": null
},
{
"_links": {
"assignee": {
"href": "/user/demo"
},
"execution": {
"href": "/execution/412a03b7-06ae-11ea-8860-120ef5ab2c25"
},
"identityLink": {
"href": "/task/412a2aca-06ae-11ea-8860-120ef5ab2c25/identity-links"
},
"processDefinition": {
"href": "/process-definition/quickEvaluation:1:129ce2b1-0616-11ea-8860-120ef5ab2c25"
},
"processInstance": {
"href": "/process-instance/412a03b7-06ae-11ea-8860-120ef5ab2c25"
},
"self": {
"href": "/task/412a2aca-06ae-11ea-8860-120ef5ab2c25"
}
},
"_embedded": {
"variable": [
{
"_links": {
"self": {
"href": "/process-instance/412a03b7-06ae-11ea-8860-120ef5ab2c25/variables/loanAmount"
}
},
"_embedded": null,
"name": "loanAmount",
"value": "650000",
"type": "String",
"valueInfo": {}
},
{
"_links": {
"self": {
"href": "/process-instance/412a03b7-06ae-11ea-8860-120ef5ab2c25/variables/firstName"
}
},
"_embedded": null,
"name": "firstName",
"value": "Kamesh",
"type": "String",
"valueInfo": {}
}
]
},
"id": "412a2aca-06ae-11ea-8860-120ef5ab2c25",
"name": "Quick Evaluation",
"assignee": "demo",
"created": "2019-11-14T07:13:27.558+0000",
"due": null,
"followUp": null,
"delegationState": null,
"description": null,
"executionId": "412a03b7-06ae-11ea-8860-120ef5ab2c25",
"owner": null,
"parentTaskId": null,
"priority": 50,
"processDefinitionId": "quickEvaluation:1:129ce2b1-0616-11ea-8860-120ef5ab2c25",
"processInstanceId": "412a03b7-06ae-11ea-8860-120ef5ab2c25",
"taskDefinitionKey": "QuickEvaluation",
"caseExecutionId": null,
"caseInstanceId": null,
"caseDefinitionId": null,
"suspended": false,
"formKey": "a8apps:suryoday:gng:v0.1.0:kycUpload",
"tenantId": null
}
]
},
"count": 13
}
Here is urlrequest:
// MARK: - URLRequestConvertible
func asURLRequest() throws -> URLRequest {
let url = try K.ProductionServer.baseURL.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
print(urlRequest)
// HTTP Method
urlRequest.httpMethod = method.rawValue
let authToken = UserDefaults.standard.string(forKey: "authToken")
let bearerToken: String = "Bearer " + (authToken ?? "")
print("baearer token::\(bearerToken)")
// Common Headers
urlRequest.setValue(ContentType.json.rawValue, forHTTPHeaderField: HTTPHeaderField.acceptType.rawValue)
urlRequest.setValue(ContentType.json.rawValue, forHTTPHeaderField: HTTPHeaderField.contentType.rawValue)
urlRequest.setValue(bearerToken, forHTTPHeaderField: HTTPHeaderField.authentication.rawValue)
// Parameters
if let parameters = parameters {
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
}
return urlRequest
}
Here is alamofire request:
import Foundation
import Alamofire
public class APIClient {
#discardableResult
private static func performRequest<T:Decodable>(route:APIRouter, decoder: JSONDecoder = JSONDecoder(), completion:#escaping (AFResult<T>)->Void) -> DataRequest {
return AF.request(route)
.responseDecodable (decoder: decoder){ (response: AFDataResponse<T>) in
completion(response.result)
print("framework response::",response.result)
}
}
public static func taskID(id: String, completion:#escaping (AFResult< [TaskID]>)->Void) {
performRequest(route: APIRouter.TaskById(id: id), completion: completion)
}
}//APIClient
Initially it shows Dictionary, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary but found an array instead. but now i'm getting nil in console log. Do not know why i'm getting nil value. Is struct is correct based on my json response? I'm struggling with getting the nested data.
Any help much appreciated pls..
Your struct is correct. See playground below for proof; I don't get an error. nil is very common result when you don't have the entire data set and you assume that some optional field in the response is non optional just because you see it in your sample data (your sample is not necessarily representative). Absent an actual spec from the server, you need to figure out what field is failing to decode and you may need to get a bunch of data to figure out which fields are really optional. You can do that by either putting in error handling code in your AF project above or just by pasting your response into my playground below. Either way the decoding error should tell you which field was not present.
import PlaygroundSupport
import UIKit
import WebKit
public struct TaskID: Decodable {
let embedded: Embedded?
let count: Int?
enum CodingKeys: String, CodingKey {
case count = "count"
case embedded = "_embedded"
}
}
public struct Embedded: Decodable {
let task: [Task]?
enum CodingKeys: String, CodingKey {
case task = "task"
}
}
public struct Task : Decodable {
let id : String?
let name: String?
let assignee: String?
let created: String?
let processDefinitionId: String?
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
case assignee = "assignee"
case created = "created"
case processDefinitionId = "processDefinitionId"
}
}
let data = """
{
"_links": {
"self": {
"href": "/task"
}
},
"_embedded": {
"task": [
{
"_links": {
"assignee": {
"href": "/user/demo"
},
"execution": {
"href": "/execution/1b64cf75-0616-11ea-8860-120ef5ab2c25"
},
"identityLink": {
"href": "/task/1b64f688-0616-11ea-8860-120ef5ab2c25/identity-links"
},
"processDefinition": {
"href": "/process-definition/quickEvaluation:1:129ce2b1-0616-11ea-8860-120ef5ab2c25"
},
"processInstance": {
"href": "/process-instance/1b64cf75-0616-11ea-8860-120ef5ab2c25"
},
"self": {
"href": "/task/1b64f688-0616-11ea-8860-120ef5ab2c25"
}
},
"_embedded": {
"variable": []
},
"id": "1b64f688-0616-11ea-8860-120ef5ab2c25",
"name": "Quick Evaluation",
"assignee": "demo",
"created": "2019-11-13T13:04:20.687+0000",
"due": null,
"followUp": null,
"delegationState": null,
"description": null,
"executionId": "1b64cf75-0616-11ea-8860-120ef5ab2c25",
"owner": null,
"parentTaskId": null,
"priority": 50,
"processDefinitionId": "quickEvaluation:1:129ce2b1-0616-11ea-8860-120ef5ab2c25",
"processInstanceId": "1b64cf75-0616-11ea-8860-120ef5ab2c25",
"taskDefinitionKey": "QuickEvaluation",
"caseExecutionId": null,
"caseInstanceId": null,
"caseDefinitionId": null,
"suspended": false,
"formKey": "a8apps:suryoday:gng:v0.1.0:kycUpload",
"tenantId": null
},
{
"_links": {
"assignee": {
"href": "/user/demo"
},
"execution": {
"href": "/execution/412a03b7-06ae-11ea-8860-120ef5ab2c25"
},
"identityLink": {
"href": "/task/412a2aca-06ae-11ea-8860-120ef5ab2c25/identity-links"
},
"processDefinition": {
"href": "/process-definition/quickEvaluation:1:129ce2b1-0616-11ea-8860-120ef5ab2c25"
},
"processInstance": {
"href": "/process-instance/412a03b7-06ae-11ea-8860-120ef5ab2c25"
},
"self": {
"href": "/task/412a2aca-06ae-11ea-8860-120ef5ab2c25"
}
},
"_embedded": {
"variable": [
{
"_links": {
"self": {
"href": "/process-instance/412a03b7-06ae-11ea-8860-120ef5ab2c25/variables/loanAmount"
}
},
"_embedded": null,
"name": "loanAmount",
"value": "650000",
"type": "String",
"valueInfo": {}
},
{
"_links": {
"self": {
"href": "/process-instance/412a03b7-06ae-11ea-8860-120ef5ab2c25/variables/firstName"
}
},
"_embedded": null,
"name": "firstName",
"value": "Kamesh",
"type": "String",
"valueInfo": {}
}
]
},
"id": "412a2aca-06ae-11ea-8860-120ef5ab2c25",
"name": "Quick Evaluation",
"assignee": "demo",
"created": "2019-11-14T07:13:27.558+0000",
"due": null,
"followUp": null,
"delegationState": null,
"description": null,
"executionId": "412a03b7-06ae-11ea-8860-120ef5ab2c25",
"owner": null,
"parentTaskId": null,
"priority": 50,
"processDefinitionId": "quickEvaluation:1:129ce2b1-0616-11ea-8860-120ef5ab2c25",
"processInstanceId": "412a03b7-06ae-11ea-8860-120ef5ab2c25",
"taskDefinitionKey": "QuickEvaluation",
"caseExecutionId": null,
"caseInstanceId": null,
"caseDefinitionId": null,
"suspended": false,
"formKey": "a8apps:suryoday:gng:v0.1.0:kycUpload",
"tenantId": null
}
]
},
"count": 13
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
do {
let decoded = try decoder.decode(TaskID.self, from: data)
print(decoded)
} catch ( let error ) {
print(error.localizedDescription)
}
import Foundation
// MARK: - Task
struct Task: Codable {
let links: VariableLinks?
let embedded: TaskEmbedded?
let count: Int?
enum CodingKeys: String, CodingKey {
case links = "_links"
case embedded = "_embedded"
case count = "count"
}
}
// MARK: - TaskEmbedded
struct TaskEmbedded: Codable {
let task: [TaskElement]?
enum CodingKeys: String, CodingKey {
case task = "task"
}
}
// MARK: - TaskElement
struct TaskElement: Codable {
let links: TaskLinks?
let embedded: TaskEmbeddedClass?
let id: String?
let name: String?
let assignee: String?
let created: String?
let due: String?
let followUp: String?
let delegationState: String?
let taskDescription: String?
let executionId: String?
let owner: String?
let parentTaskId: Int?
let priority: Int?
let processDefinitionId: String?
let processInstanceId: String?
let taskDefinitionKey: String?
let caseExecutionId: Int?
let caseInstanceId: Int?
let caseDefinitionId: Int?
let suspended: Bool?
let formKey: String?
let tenantId: Int?
enum CodingKeys: String, CodingKey {
case links = "_links"
case embedded = "_embedded"
case id = "id"
case name = "name"
case assignee = "assignee"
case created = "created"
case due = "due"
case followUp = "followUp"
case delegationState = "delegationState"
case taskDescription = "description"
case executionId = "executionId"
case owner = "owner"
case parentTaskId = "parentTaskId"
case priority = "priority"
case processDefinitionId = "processDefinitionId"
case processInstanceId = "processInstanceId"
case taskDefinitionKey = "taskDefinitionKey"
case caseExecutionId = "caseExecutionId"
case caseInstanceId = "caseInstanceId"
case caseDefinitionId = "caseDefinitionId"
case suspended = "suspended"
case formKey = "formKey"
case tenantId = "tenantId"
}
}
// MARK: - TaskEmbeddedClass
struct TaskEmbeddedClass: Codable {
let variable: [Variable]?
enum CodingKeys: String, CodingKey {
case variable = "variable"
}
}
// MARK: - Variable
struct Variable: Codable {
let links: VariableLinks?
let embedded: String?
let name: String?
let value: String?
let type: String?
let valueInfo: ValueInfo?
enum CodingKeys: String, CodingKey {
case links = "_links"
case embedded = "_embedded"
case name = "name"
case value = "value"
case type = "type"
case valueInfo = "valueInfo"
}
}
// MARK: - VariableLinks
struct VariableLinks: Codable {
let linksSelf: SelfClass?
enum CodingKeys: String, CodingKey {
case linksSelf = "self"
}
}
// MARK: - SelfClass
struct SelfClass: Codable {
let href: String?
enum CodingKeys: String, CodingKey {
case href = "href"
}
}
// MARK: - ValueInfo
struct ValueInfo: Codable {
}
// MARK: - TaskLinks
struct TaskLinks: Codable {
let assignee: SelfClass?
let execution: SelfClass?
let identityLink: SelfClass?
let processDefinition: SelfClass?
let processInstance: SelfClass?
let linksSelf: SelfClass?
enum CodingKeys: String, CodingKey {
case assignee = "assignee"
case execution = "execution"
case identityLink = "identityLink"
case processDefinition = "processDefinition"
case processInstance = "processInstance"
case linksSelf = "self"
}
}
Also, if you feeling lazy you can use quicktype.io, As nil is a very common response from decodable, you can you an extension for DataRequest to parse and get the values from the request just like using responseDecodable, here you can use something like this,
extension DataRequest {
fileprivate func decodableResponseSerializer<T: Decodable>() -> DataResponseSerializer<T> {
return DataResponseSerializer { _, response, data, error in
guard error == nil else { return .failure(error!) }
guard let data = data else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
}
return Result { try newJSONDecoder().decode(T.self, from: data) }
}
}
#discardableResult
fileprivate func responseDecodable<T: Decodable>(queue: DispatchQueue? = nil, completionHandler: #escaping (DataResponse<T>) -> Void) -> Self {
return response(queue: queue, responseSerializer: decodableResponseSerializer(), completionHandler: completionHandler)
}
}
and then you can call it like this
Alamofire.request(url, method:.post, parameters: parameters, headers: headers)
.responseDecodable { (response: DataResponse< Task >) in completion(response.result) }
as you were getting something like this, it only comes when you have a different type of data rather than which you have specified.
Related
I am trying to fetch data from the Unsplash API however I am getting the following error: "Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates."
Here is the model struct:
// MARK: - UnsplashData
struct UnsplashData: Codable {
let id: String
let createdAt, updatedAt, promotedAt: Date
let width, height: Int
let color, blurHash: String
let unsplashDataDescription: String?
let altDescription: String
let urls: Urls
let links: UnsplashDataLinks
let categories: [String]
let likes: Int
let likedByUser: Bool
let currentUserCollections: [String]
let sponsorship: JSONNull?
let user: User
let exif: Exif
let location: Location
let views, downloads: Int
enum CodingKeys: String, CodingKey {
case id
case createdAt = "created_at"
case updatedAt = "updated_at"
case promotedAt = "promoted_at"
case width, height, color
case blurHash = "blur_hash"
case unsplashDataDescription = "description"
case altDescription = "alt_description"
case urls, links, categories, likes
case likedByUser = "liked_by_user"
case currentUserCollections = "current_user_collections"
case sponsorship, user, exif, location, views, downloads
}
}
// MARK: - Exif
struct Exif: Codable {
let make, model, exposureTime, aperture: String
let focalLength: String
let iso: Int
enum CodingKeys: String, CodingKey {
case make, model
case exposureTime = "exposure_time"
case aperture
case focalLength = "focal_length"
case iso
}
}
// MARK: - UnsplashDataLinks
struct UnsplashDataLinks: Codable {
let linksSelf, html, download, downloadLocation: String
enum CodingKeys: String, CodingKey {
case linksSelf = "self"
case html, download
case downloadLocation = "download_location"
}
}
// MARK: - Location
struct Location: Codable {
let title, name, city, country: String?
let position: Position
}
// MARK: - Position
struct Position: Codable {
let latitude, longitude: Double?
}
// MARK: - Urls
struct Urls: Codable {
let raw, full, regular, small: String
let thumb: String
}
// MARK: - User
struct User: Codable {
let id: String
let updatedAt: Date
let username, name, firstName, lastName: String
let twitterUsername: String?
let portfolioURL: String
let bio: String?
let location: String
let links: UserLinks
let profileImage: ProfileImage
let instagramUsername: String
let totalCollections, totalLikes, totalPhotos: Int
let acceptedTos: Bool
enum CodingKeys: String, CodingKey {
case id
case updatedAt = "updated_at"
case username, name
case firstName = "first_name"
case lastName = "last_name"
case twitterUsername = "twitter_username"
case portfolioURL = "portfolio_url"
case bio, location, links
case profileImage = "profile_image"
case instagramUsername = "instagram_username"
case totalCollections = "total_collections"
case totalLikes = "total_likes"
case totalPhotos = "total_photos"
case acceptedTos = "accepted_tos"
}
}
// MARK: - UserLinks
struct UserLinks: Codable {
let linksSelf, html, photos, likes: String
let portfolio, following, followers: String
enum CodingKeys: String, CodingKey {
case linksSelf = "self"
case html, photos, likes, portfolio, following, followers
}
}
// MARK: - ProfileImage
struct ProfileImage: Codable {
let small, medium, large: String
}
// MARK: - Encode/decode helpers
class JSONNull: Codable, Hashable {
public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
return true
}
public var hashValue: Int {
return 0
}
public func hash(into hasher: inout Hasher) {
// No-op
}
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
And here is my ObservableObject:
class UnsplashAPI: ObservableObject {
enum State {
case loading
case loaded(UnsplashData)
}
#Published var state = State.loading
let url = URL(string: "https://api.unsplash.com/")!
func request() {
guard var components = URLComponents(url: url.appendingPathComponent("photos/random"),
resolvingAgainstBaseURL: true)
else {
fatalError("Couldn't append path component")
}
components.queryItems = [
URLQueryItem(name: "client_id", value: "vMDQ3Vzix8FN6MJL5Qpl3y0F7GdQsTtOjBe_L-IG2ro")
]
let request = URLRequest(url: components.url!)
let urlSession = URLSession(configuration: URLSessionConfiguration.default)
urlSession.dataTask(with: request) { data, urlResponse, error in
if let data = data {
let decoder = JSONDecoder()
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
decoder.dateDecodingStrategy = .formatted(dateFormatter)
do {
let response = try decoder.decode(UnsplashData.self, from: data)
self.state = .loaded(response) //error here
} catch {
print(error)
fatalError("Couldn't decode")
}
} else if let error = error {
print(error.localizedDescription)
} else {
fatalError("Didn't receive data")
}
}.resume()
}
}
Finally here is an example response I requested using Postman:
{
"id": "HWx5PYGudcI",
"created_at": "2020-12-08T22:11:11-05:00",
"updated_at": "2020-12-26T23:19:29-05:00",
"promoted_at": "2020-12-09T03:14:06-05:00",
"width": 4000,
"height": 6000,
"color": "#8ca6a6",
"blur_hash": "LAD,r_D*_M?^%ER4%$-oyYp0m+WE",
"description": null,
"alt_description": "boy in gray crew neck shirt",
"urls": {
"raw": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1",
"full": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?crop=entropy&cs=srgb&fm=jpg&ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=85",
"regular": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=1080",
"small": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=400",
"thumb": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=200"
},
"links": {
"self": "https://api.unsplash.com/photos/HWx5PYGudcI",
"html": "https://unsplash.com/photos/HWx5PYGudcI",
"download": "https://unsplash.com/photos/HWx5PYGudcI/download",
"download_location": "https://api.unsplash.com/photos/HWx5PYGudcI/download"
},
"categories": [],
"likes": 51,
"liked_by_user": false,
"current_user_collections": [],
"sponsorship": null,
"user": {
"id": "3Bj-zCFL4-g",
"updated_at": "2020-12-26T14:58:36-05:00",
"username": "owensito",
"name": "Owen Vangioni",
"first_name": "Owen",
"last_name": "Vangioni",
"twitter_username": null,
"portfolio_url": null,
"bio": "Capturing magical moments...\nInstagram: #owensitens 18 years",
"location": "Argentina ",
"links": {
"self": "https://api.unsplash.com/users/owensito",
"html": "https://unsplash.com/#owensito",
"photos": "https://api.unsplash.com/users/owensito/photos",
"likes": "https://api.unsplash.com/users/owensito/likes",
"portfolio": "https://api.unsplash.com/users/owensito/portfolio",
"following": "https://api.unsplash.com/users/owensito/following",
"followers": "https://api.unsplash.com/users/owensito/followers"
},
"profile_image": {
"small": "https://images.unsplash.com/profile-1583211530737-0c1a46227535image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=32&w=32",
"medium": "https://images.unsplash.com/profile-1583211530737-0c1a46227535image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=64&w=64",
"large": "https://images.unsplash.com/profile-1583211530737-0c1a46227535image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=128&w=128"
},
"instagram_username": "owensitens",
"total_collections": 1,
"total_likes": 13,
"total_photos": 135,
"accepted_tos": true
},
"exif": {
"make": "NIKON CORPORATION",
"model": "NIKON D3300",
"exposure_time": "1/320",
"aperture": "5.3",
"focal_length": "45.0",
"iso": 200
},
"location": {
"title": null,
"name": null,
"city": null,
"country": null,
"position": {
"latitude": null,
"longitude": null
}
},
"views": 536045,
"downloads": 1267
}
You will need to switch thread to the main thread from which you are allowed (and only from it!) to make UI changes in iOS. To fix the error you will need to use GCD and simply wrap the line where you change your state in the async closure block.
DispatchQueue.main.async {
self.state = .loaded(response) // error should not be triggered anymore
}
add #MainActor before your class definition.
I writing because I need to search a json-key passed in a function like a string. Do you have any suggestion on how I could implement it? Once I find the key I also need to edit the value. Here there is the code I wrote until now:
JSON:
{
"JSONRoot": {
"version": 1,
"Town": {
"hour": 0,
"latitude": "",
"longitude": 0,
"latitudine": 0
},
"MeasurePoints": {
"MeasurePoint": [
{
"code": "",
"codelocation": "",
}
]
},
"Wakeup": {
"startH": 6,
"startM": 0,
"maxAttempts": 3,
"maxRetry": 10
},
"Config": {
"port": 12345,
"A": {
"writable": true,
"value": 12
},
"B": {
"writable": true,
"value": 8
},
},
"Sales": {
"Stores": {
"Store": [
{
"description": "A description",
"type": "1",
"Floors": {
"basement": true,
"number": 2
},
"Doors": {
"type": "",
"number": 7
},
"Lights": {
"number": 20
}
},
{
"description": "A description",
"type": "4",
"Floors": {
"basement": none,
"number": 1
},
"Doors": {
"type": "",
"number": 4
},
"Lights": {
"number": 8
}
}
]
}
}
}
}
Structs with codable:
// MARK: - JSONConfig
struct JsonConfig: Codable {
let jsonRoot: JSONRoot?
enum CodingKeys: String, CodingKey {
case jsonRoot = "JSONRoot"
}
}
// MARK: - JSONRoot
struct JSONRoot: Codable {
let version: Int?
let measurePoints: MeasurePoints?
let wakeup: Wakeup?
let config: Config?
let sale: Sale?
enum CodingKeys: String, CodingKey {
case version
case measurePoints = "MeasurePoints"
case wakeup = "Wakeup"
case config = "Config"
case sale = "Sale"
}
}
// MARK: - Stores
struct Stores: Codable {
let stores: [Store]?
enum CodingKeys: String, CodingKey {
case stores = "Stores"
}
}
// MARK: - Store
struct Store: Codable {
let storeDescription: String?
let type: Int?
let floors: Floors?
let doors: Doors?
let lights: Lights?
enum CodingKeys: String, CodingKey {
case storeDescription = "description"
case type
case floors = "Floors"
case doors = "Doors"
case lights = "Lights"
}
}
// MARK: - Floors
struct Floors: Codable {
let basement: Bool?
let number: Int?
}
// MARK: - Doors
struct Doors: Codable {
let type: String?
let number: Int?
}
// MARK: - Lights
struct Lights: Codable {
let number: Int?
}
// MARK: - MeasurePoints
struct MeasurePoints: Codable {
let measurePoint: [MeasurePoint]?
enum CodingKeys: String, CodingKey {
case measurePoint = "MeasurePoint"
}
}
// MARK: - MeasurePoint
struct MeasurePoint: Codable {
let code, codeLocation: String?
}
// MARK: - Config
struct Config: Codable {
let port: Int?
let a, b: K?
enum CodingKeys: String, CodingKey {
case port
case a = "A"
case b = "B"
}
}
// MARK: - K
struct K: Codable {
let writable: Bool?
let value: Int?
}
// MARK: - Wakeup
struct Wakeup: Codable {
let startH, startM, maxAttempts, maxRetry: Int?
}
Function to search for a key:
func setKeyValue(jsonKey: String, value: String) {
let decoder = JSONDecoder()
let jsonData = Data(C.jsonString.utf8)
if let jsonResult = try? decoder.decode(JsonConfig.self, from: jsonData) {
// At this point I have the jsonKey = "JSONRoot.Wakeup.maxRetry" but how I can use it to search for
// the key in the jsonResult?
}
}
Obviously I need to create a new struct to edit the json but one step at a time.
Using JSONSerialisation is probably the most straightforward way here
var value: Any?
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
let keys = "JSONRoot.Wakeup.maxRetry".split(separator: ".").map {String($0)}
var dict = jsonResult
for i in 0..<keys.count {
if let temp = dict[keys[i]] as? [String:Any] {
dict = temp
continue
}
value = dict[keys[i]]
}
}
} catch {
print(error)
}
Note that this doesn't support arrays but a solution for that is very dependent on how the search key syntax would handle an array
If my thinking is correct as you, you can try with this code.
override func viewDidLoad() {
super.viewDidLoad()
let jsonString = """
{
"JSONRoot": {
"version": 1,
"Town": {
"hour": 0,
"latitude": "",
"longitude": 0,
"latitudine": 0
},
"MeasurePoints": {
"MeasurePoint": [{
"code": "",
"codelocation": ""
}]
},
"Wakeup": {
"startH": 6,
"startM": 0,
"maxAttempts": 3,
"maxRetry": 10
},
"Config": {
"port": 12345,
"A": {
"writable": true,
"value": 12
}
},
"Sales": {
"Stores": {
"Store": [{
"description": "A description",
"type": "1",
"Floors": {
"basement": true,
"number": 2
},
"Doors": {
"type": "",
"number": 7
},
"Lights": {
"number": 20
}
},
{
"description": "A description",
"type": "4",
"Floors": {
"basement": "none",
"number": 1
},
"Doors": {
"type": "",
"number": 4
},
"Lights": {
"number": 8
}
}
]
}
}
}
}
"""
editJson(jsonString)
}
func editJson(_ jsonString: String) {
do{
let jsonData = Data(jsonString.utf8)
var jsonObject = try JSONSerialization.jsonObject(with: jsonData)
parseDict(&jsonObject)
print("jsonObject: \(String(describing: jsonObject))")
}catch let error {
print(error.localizedDescription)
}
}
func parseDict(_ jsonObject: inout Any) {
if let _ = jsonObject as? String {
return
} else if var dictionary = jsonObject as? Dictionary<String, Any> {
for (key, value) in dictionary {
var nextObject = value
parseDict(&nextObject)
if let value = getValueWith(key), let _ = dictionary.removeValue(forKey: key) {
dictionary[key] = value
} else {
dictionary[key] = nextObject
}
}
jsonObject = dictionary
}else if let array = jsonObject as? Array<Any> {
var updatedArray = array
for (index, value) in array.enumerated() {
var nextObject = value
parseDict(&nextObject)
updatedArray[index] = nextObject
}
jsonObject = updatedArray
}
}
func getValueWith(_ key: String) -> String? {
return [
"description" : "Amit (amitpstu1#gmail.com) ... so on"
][key]
}
You can refresh your memory or learn more here:
https://developer.apple.com/documentation/foundation/archives_and_serialization/using_json_with_custom_types
You would be looking at merge json from different depths section. Using encodable extension etc.
You could also look here: In Swift, can one use a string to access a struct property? If you want to roll your own search function, like a modified dfs or something.
I'm accessing the data from an API with XCode(10.2.1) and Swift(5.0) and ran into a problem I cannot seem to find the answer to. I am able to get data from all other parts of the API apart from one, which has been named as a number string "750", im not sure how to grab that data when I can't use a variable that jsonDecoder can read?
This is an example of what I know won't work but gives you an idea of what I'm trying to do.
class Images: Codable {
let "750": String
init("750": String){
self."750" = "750"
}
}
Here's a snippet from the API I'm trying to get the images from:
"id": "069f7f26",
"sku": "AP",
"title": "Pizza",
"description": "A really great pizza",
"list_price": "9.95",
"is_vatable": true,
"is_for_sale": false,
"age_restricted": false,
"box_limit": 2,
"always_on_menu": false,
"volume": null,
"zone": null,
"created_at": "2017-03-06T10:52:43+00:00",
"attributes": [
{
"id": "670f0e7c",
"title": "Allergen",
"unit": null,
"value": "Products manufactured in a nut environment"
},
{
"id": "c29e7",
"title": "Weight",
"unit": "g",
"value": "300"
}
],
"tags": [
],
"images": {
"750": {
"src": "https:\/\/some_website.co.uk\/cms\/product_image\some_image.jpg",
"url": "https:\/\/some_website.co.uk\/cms\/product_image\some_image.jpg",
"width": 750
}
}
},
I setup an example that better match your situation in order to give you an overview on how to parse and access your JSON information dynamically with a Dictionary data type:
import Foundation
let jsonData = """
{
"images": {
"750": {
"src": "https:\\/\\/some_website.co.uk/cms/product_image/some_image.jpg",
"url": "https:\\/\\/some_website.co.uk/cms/product_image/some_image.jpg",
"width": 750
}
}
}
"""
let json = jsonData.data(using: .utf8)!
public struct Results: Codable {
public var images: [String:Image] = [:]
enum CodingKeys: String, CodingKey {
case images = "images"
}
}
public struct Image: Codable {
public var src: String = ""
public var url: String = ""
public var width: Int = 0
enum CodingKeys: String, CodingKey {
case src = "src"
case url = "url"
case width = "width"
}
}
if let results = try? JSONDecoder().decode(Results.self, from: json) {
let imagesDict = results.images
for (key, value) in imagesDict {
print("Key: \(key)")
print("Value: \(value)")
}
}
If you try this snippet it will give you this output printed:
Key: 750
Value: Image(src: "https://some_website.co.uk/cms/product_image/some_image.jpg", url: "https://some_website.co.uk/cms/product_image/some_image.jpg", width: 750)
You can try out the snippet above online, if you copy paste it here and run it: http://online.swiftplayground.run/
### UPDATE (in response to comment)
In response to your comment, I found it easier to setup another example to show you how you can achieve that with your exact code sample that you shared in the comment itself.
I left everything as class and just added images in order to leave you an overview on how to achieve that.
In the end, I'd suggest to rename Products and Attributes into Product and Attribute. Also if there is no strong reason on why you choosed the model to be class, just change them to struct and as well if there is no strong reasons to keep most of the attributes of each model optional give them a default value as I did in the example above if you are always expecting some values/attributes to be there.
You can try and run this snippet as well in http://online.swiftplayground.run to try it out:
import Foundation
let jsonData = """
{
"data": [
{
"title": "titlex",
"description": "descx",
"list_price": "123,456",
"attributes": [
{
"title": "titlex",
"unit": "unitx",
"value": "valuex"
}
],
"images": {
"750": {
"src": "https:\\/\\/some_website.co.uk/cms/product_image/some_image.jpg",
"url": "https:\\/\\/some_website.co.uk/cms/product_image/some_image.jpg",
"width": 750
}
}
}
]
}
"""
let json = jsonData.data(using: .utf8)!
class AllProducts: Codable {
let data: [Products]
init(data: [Products]) {
self.data = data
}
}
class Products: Codable {
let title: String?
let description: String?
let list_price: String?
let attributes: [Attributes]?
let images: [String:Image]?
init(title: String, description: String, list_price: String, attributes: [Attributes], images: [String:Image]) {
self.title = title
self.description = description
self.list_price = list_price
self.attributes = attributes
self.images = images
}
}
class Attributes: Codable {
let title: String?
let unit: String?
let value: String?
init(title: String, unit: String, value: String) {
self.title = title
self.unit = unit
self.value = value
}
}
class Image: Codable {
let src: String?
let url: String?
let width: Int?
init(src: String, url: String, width: Int) {
self.src = src
self.url = url
self.width = width
}
}
// parsing/decoding
if let results = try? JSONDecoder().decode(AllProducts.self, from: json) {
if let imagesDict = results.data[0].images {
// there is an "images" for product at position 0 (the only one in my json example)
for (key, value) in imagesDict {
print("Key: \(key)")
print("Value src: \(value.src)")
print("Value url: \(value.url)")
print("Value width: \(value.width)")
}
}
}
Output
Key: 750
Value src: Optional("https://some_website.co.uk/cms/product_image/some_image.jpg")
Value url: Optional("https://some_website.co.uk/cms/product_image/some_image.jpg")
Value width: Optional(750)
So i try to parse with jsondecoder and when i see in the log menu, all the data in json is nil. While the json i check in postman all have data on it
so here's the json i want to parse (*i just want to parse the row) :
{
" user": {
"command": "SELECT",
"rowCount": 1,
"oid": null,
"rows": [
{
"user_id": 193,
"u_name": "Gunawan Wibisono",
"email": "gunwibi89#gmail.com",
"div_name": "Design Aplication & Infrastructure",
"url": "2"
}
],
"fields": [
{
"name": "user_id",
"tableID": 1656774,
"columnID": 1,
"dataTypeID": 23,
"dataTypeSize": 4,
"dataTypeModifier": -1,
"format": "text"
},
{
"name": "u_name",
"tableID": 1656774,
"columnID": 2,
"dataTypeID": 1043,
"dataTypeSize": -1,
"dataTypeModifier": 54,
"format": "text"
},
{
"name": "email",
"tableID": 1656774,
"columnID": 3,
"dataTypeID": 1043,
"dataTypeSize": -1,
"dataTypeModifier": 259,
"format": "text"
},
{
"name": "div_name",
"tableID": 1656724,
"columnID": 2,
"dataTypeID": 1043,
"dataTypeSize": -1,
"dataTypeModifier": 259,
"format": "text"
},
{
"name": "url",
"tableID": 1656774,
"columnID": 9,
"dataTypeID": 1043,
"dataTypeSize": -1,
"dataTypeModifier": 259,
"format": "text"
}
],
"_parsers": [
null,
null,
null,
null,
null
],
"_types": {
"_types": {
"arrayParser": {}
},
"text": {},
"binary": {}
},
"RowCtor": null,
"rowAsArray": false
},
"status": 1
}
this is the code :
struct User : Codable {
let command : String?
let rowCount : Int?
let oid : Int?
let rows : [Rowss]?
}
struct Rowss : Codable {
let user_id: Int?
let u_name : String?
let email : String?
let div_name: String?
let url : String?
enum Codingkeys : String, CodingKey {
case user_id = "user_id"
case u_name = "u_name"
case email = "email"
case div_name = "div_name"
case url = "url"
}
}
func Json() {
let user = UserName.text
let pass = Password.text
let json = "http://ratings.immobispsa.com/getslogs/\(user!)/\(pass!)"
guard let myUrl = URL(string: json) else { return }
URLSession.shared.dataTask(with: myUrl) { (data, response, error) in
guard let data = data else {return}
do{
let user = try JSONDecoder().decode(User.self, from: data)
print("this is the json\(user)")
}catch{
print(error)
}
}.resume()
this is the log menu after i build :
"this is the jsonUser(command: nil, rowCount: nil, oid: nil, rows: nil)"
any idea where ive done wrong?
Your Codable structure is wrong. You should refer some tutorials for the same. Here is the Codable structure as per your response:
struct UserResponse: Codable {
let status: Int
let user: User
private enum CodingKeys: String, CodingKey {
case status
case user = " user"
}
}
struct User: Codable {
let command: String?
let rowCount: Int?
let oid: Int?
let rowCtor: Int?
let rowAsArray: Bool?
let rows: [Rows]?
let fields: [Fields]?
let parsers: [Parsers]?
let types: Type?
private enum CodingKeys: String, CodingKey {
case command
case rowCount
case oid
case rowCtor = "RowCtor"
case rowAsArray
case rows
case fields
case parsers = "_parsers"
case types = "_types"
}
}
struct Rows: Codable {
let userId: Int
let uName: String
let email: String
let divName: String
let url: String
private enum CodingKeys: String, CodingKey {
case userId = "user_id"
case uName = "u_name"
case email
case divName = "div_name"
case url
}
}
struct Fields: Codable {
let name: String
let tableID: Int
let columnID: Int
let datatypeID: Int?
let dataTypeSize: Int
let dataTypeModifier: Int
let format: String
private enum CodingKeys: String, CodingKey {
case name
case tableID
case columnID
case datatypeID
case dataTypeSize
case dataTypeModifier
case format
}
}
struct Parsers: Codable {
}
struct Types: Codable {
let types: Type?
let text: Text?
let binary: Binary?
private enum CodingKeys: String, CodingKey {
case types = "_types"
case text
case binary
}
}
struct Type: Codable {
}
struct Text: Codable {
}
struct Binary: Codable {
}
If any value can come as null, then only mark it as optional (?) otherwise don't, and in JSON your user key is having extra space at the front like " user", your API developer should fix it if possible.
Now decode it:
do{
let decodeResponse = try JSONDecoder().decode(UserResponse.self, from: data)
print("this is the json\(decodeResponse.user)")
}catch{
print(error)
}
I am trying to parse JSON using decodable in Swift 4
The JSON is as below:
{
"_id": {
"$oid": "5afceaa0c1743f37b4ee1cf8"
},
"Con_id": "xxx",
"S_id": "xxx",
"I_Image": [
{
"$binary": {
"base64": "",
"subType": "00"
}
}
],
"T_Agreements": [
{
"Ag_Type": "xxx",
"Ap_Type": "xxx",
"Header": {
"Date": {
"$numberInt": "0"
},
"Company": "xxx",
"O_Code": "xxx",
"Lo": "xxx",
"Completed": true
},
"T_Particular": {
"C_Name": "NA",
"C_Address": "NA",
"C_Landline": "NA",
"ROC": "NA",
"T_Name": "xxx",
"Gender": "M",
"NR": "xxx",
"Dob": "22/08/1977",
"C_No": "xxx",
"T_Address": "xxx",
"S_No": "xxx",
"Sign": "NA",
"Proposed": "xxx",
"Completed": true
},
"D_Agreement": {
"C_Period": {
"P_Yr": {
"$numberInt": "2"
},
"P_Mth": {
"$numberInt": "0"
},
"From": {
"$numberInt": "0"
},
"To": {
"$numberInt": "0"
}
},
"First_Term": {
"R_A": {
"$numberInt": "800000"
},
"From_Date": {
"$numberInt": "0"
},
"To_Date": {
"$numberInt": "0"
}
},
"Second_Term": {
"R_A": "0",
"From_Date": {
"$numberInt": "0"
},
"To_Date": {
"$numberInt": "0"
}
},
"S_D": {
"$numberInt": "800"
},
"S_D_M": {
"$numberInt": "0"
},
"C_F": {
"$numberInt": "0"
},
"D_C_F": {
"$numberInt": "0"
},
"Maintenance_Fee": {
"$numberInt": "0"
},
"Others": {
"Description": "NA",
"O_F": {
"$numberInt": "0"
}
},
"D_C": "NA",
"Completed": true
},
"T_S": {
"$binary": {
"base64": "",
"subType": "00"
}
},
"L_Rep": {
"Name": "xxx",
"Rep_Sig": {
"$binary": {
"base64": "",
"subType": "00"
}
}
},
"Remarks": ""
}
],
"Supp": {
"B_N": "xxx",
"B_O_H": "12",
"C_B_O": "xxx",
"A_S": "Nil",
"F_T_Description": "xxx",
"C_T": "xxx",
"Completed": true
},
"FAdjustment": [
{
"Date": {
"$numberInt": "0"
},
"R_Increased": true,
"Pro_R": {
"$numberInt": "20066660"
},
"A_P_From": {
"$numberInt": "0"
},
"A_P_To": {
"$numberInt": "0"
},
"E_Date": {
"$numberInt": "0"
},
"A_Reason": "xxx",
"Req": {
"Name": "xxx",
"Des": "xxx",
"Sig": {
"$binary": {
"base64": "",
"subType": "00"
}
},
"Date": {
"$numberInt": "0"
}
},
"A1": {
"Name": "xxx",
"Des": "xxx",
"Sig": {
"$binary": {
"base64": "",
"subType": "00"
}
},
"Date": {
"$numberInt": "0"
}
},
"A2": {
"Name": "xxx",
"Designation": "xxx",
"Sig": {
"$binary": {
"base64": "",
"subType": "00"
}
},
"Date": {
"$numberInt": "0"
}
}
}
],
"Status": "xxx",
"Re": {
"Out": "0"
},
"Termination": {
"Terminated": false,
"Reason": "NA"
}
}
I am able to easily parse things such as conID with my Struct:
struct Welcome: Codable {
let id: ID?
let conID, sID: String?
let iImage: [IImage]?
let tAgreements: [TAgreement]?
let supp: Supp?
let fAdjustment: [FAdjustment]?
let status: String?
let re: Re?
let termination: Termination?
enum CodingKeys: String, CodingKey {
case id = "_id"
case conID = "Con_id"
case sID = "S_id"
case iImage = "I_Image"
case tAgreements = "T_Agreements"
case supp = "Supp"
case fAdjustment = "FAdjustment"
case status = "Status"
case re = "Re"
case termination = "Termination"
}
}
struct FAdjustment: Codable {
let date: APFrom?
let rIncreased: Bool?
let proR, aPFrom, aPTo, eDate: APFrom?
let aReason: String?
let req, a1, a2: A1?
enum CodingKeys: String, CodingKey {
case date = "Date"
case rIncreased = "R_Increased"
case proR = "Pro_R"
case aPFrom = "A_P_From"
case aPTo = "A_P_To"
case eDate = "E_Date"
case aReason = "A_Reason"
case req = "Req"
case a1 = "A1"
case a2 = "A2"
}
}
struct A1: Codable {
let name, des: String?
let sig: IImage?
let date: APFrom?
let designation: String?
enum CodingKeys: String, CodingKey {
case name = "Name"
case des = "Des"
case sig = "Sig"
case date = "Date"
case designation = "Designation"
}
}
struct APFrom: Codable {
let numberInt: String?
enum CodingKeys: String, CodingKey {
case numberInt = "$numberInt"
}
}
struct IImage: Codable {
let binary: Binary?
enum CodingKeys: String, CodingKey {
case binary = "$binary"
}
}
struct Binary: Codable {
let base64, subType: String?
}
struct ID: Codable {
let oid: String?
enum CodingKeys: String, CodingKey {
case oid = "$oid"
}
}
struct Re: Codable {
let out: String?
enum CodingKeys: String, CodingKey {
case out = "Out"
}
}
struct Supp: Codable {
let bN, bOH, cBO, aS: String?
let fTDescription, cT: String?
let completed: Bool?
enum CodingKeys: String, CodingKey {
case bN = "B_N"
case bOH = "B_O_H"
case cBO = "C_B_O"
case aS = "A_S"
case fTDescription = "F_T_Description"
case cT = "C_T"
case completed = "Completed"
}
}
struct TAgreement: Codable {
let agType, apType: String?
let header: Header?
let tParticular: TParticular?
let dAgreement: DAgreement?
let tS: IImage?
let lRep: LRep?
let remarks: String?
enum CodingKeys: String, CodingKey {
case agType = "Ag_Type"
case apType = "Ap_Type"
case header = "Header"
case tParticular = "T_Particular"
case dAgreement = "D_Agreement"
case tS = "T_S"
case lRep = "L_Rep"
case remarks = "Remarks"
}
}
struct DAgreement: Codable {
let cPeriod: CPeriod?
let firstTerm: FirstTerm?
let secondTerm: SecondTerm?
let sD, sDM, cF, dCF: APFrom?
let maintenanceFee: APFrom?
let others: Others?
let dC: String?
let completed: Bool?
enum CodingKeys: String, CodingKey {
case cPeriod = "C_Period"
case firstTerm = "First_Term"
case secondTerm = "Second_Term"
case sD = "S_D"
case sDM = "S_D_M"
case cF = "C_F"
case dCF = "D_C_F"
case maintenanceFee = "Maintenance_Fee"
case others = "Others"
case dC = "D_C"
case completed = "Completed"
}
}
struct CPeriod: Codable {
let pYr, pMth, from, to: APFrom?
enum CodingKeys: String, CodingKey {
case pYr = "P_Yr"
case pMth = "P_Mth"
case from = "From"
case to = "To"
}
}
struct FirstTerm: Codable {
let rA, fromDate, toDate: APFrom?
enum CodingKeys: String, CodingKey {
case rA = "R_A"
case fromDate = "From_Date"
case toDate = "To_Date"
}
}
struct Others: Codable {
let description: String?
let oF: APFrom?
enum CodingKeys: String, CodingKey {
case description = "Description"
case oF = "O_F"
}
}
struct SecondTerm: Codable {
let rA: String?
let fromDate, toDate: APFrom?
enum CodingKeys: String, CodingKey {
case rA = "R_A"
case fromDate = "From_Date"
case toDate = "To_Date"
}
}
struct Header: Codable {
let date: APFrom?
let company, oCode, lo: String?
let completed: Bool?
enum CodingKeys: String, CodingKey {
case date = "Date"
case company = "Company"
case oCode = "O_Code"
case lo = "Lo"
case completed = "Completed"
}
}
struct LRep: Codable {
let name: String?
let repSig: IImage?
enum CodingKeys: String, CodingKey {
case name = "Name"
case repSig = "Rep_Sig"
}
}
struct TParticular: Codable {
let cName, cAddress, cLandline, roc: String?
let tName, gender, nr, dob: String?
let cNo, tAddress, sNo, sign: String?
let proposed: String?
let completed: Bool?
enum CodingKeys: String, CodingKey {
case cName = "C_Name"
case cAddress = "C_Address"
case cLandline = "C_Landline"
case roc = "ROC"
case tName = "T_Name"
case gender = "Gender"
case nr = "NR"
case dob = "Dob"
case cNo = "C_No"
case tAddress = "T_Address"
case sNo = "S_No"
case sign = "Sign"
case proposed = "Proposed"
case completed = "Completed"
}
}
struct Termination: Codable {
let terminated: Bool?
let reason: String?
enum CodingKeys: String, CodingKey {
case terminated = "Terminated"
case reason = "Reason"
}
}
I'm struggling with getting the nested stuff out.
How do I get things from T_Agreements like Ag_Type out individually and everything from T_Particular out individually?
I have tried
let jsonUrlString = "URL REMOVED REFER TO JSON ABOVE"
guard let url = URL(string: jsonUrlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
let welcome = try! decoder.decode(Welcome.self, from: data)
let tagree = try! decoder.decode(TAgreement.self, from: data)
print(tagree) // This returns all the header inside T_Agreements but the values are all nil
print(tagree.tParticular.cAddress) // This returns nil too
}
}.resume()
Much thanks and appreciation
The line let welcome = try! decoder.decode(Welcome.self, from: data) loads the json data into a Welcome data model, which matches the structure of the json. Trying to reload the same json data into other data models (as you do in the next line) won't work. You need to extract the data directly from the populated data models you've created.
To get TAgreements, you just grab that data from the welcome model:
let tagreements = welcome.tAgreements
To get Ag_Type out, you get the populated data from the first element of tagreements:
let agType = tagreements[0].agType