I have hit a wall that I cant find the way around. I have a JSON file that I am trying to decode but there is a part of the JSON that is missing. I always get nil even though I know that there is supposed to be data there.
This is the first part of the JSON file
{
"type": "FeatureCollection",
"name": "points",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature",
"properties": { "osm_id": "755",
"name": "Majorstuen",
"other_tags": "\"bus\"=>\"yes\",\"network\"=>\"Ruter\",\"public_transport\"=>\"stop_position\"" },
"geometry": { "type": "Point", "coordinates": [ 10.7160479, 59.9296625 ] } },
{ "type": "Feature",
"properties": { "osm_id": "1188",
"name": "Arnes",
"highway": "bus_stop",
"other_tags": "\"ref:nsrq\"=>\"82139\"" },
"geometry": { "type": "Point", "coordinates": [ 16.919517, 68.3459 ] } },
{ "type": "Feature",
"properties": { "osm_id": "1194",
"name": "Skjellneset",
"highway": "bus_stop",
"other_tags": "\"ref:nsrq\"=>\"82148\"" },
"geometry": { "type": "Point", "coordinates": [ 16.938766, 68.34916 ] } },
{ "type": "Feature",
"properties": { "osm_id": "1202",
"name": "Osen",
"highway": "bus_stop",
"other_tags": "\"ref:nsrq\"=>\"82152\"" },
"geometry": { "type": "Point", "coordinates": [ 16.952982, 68.352551 ] } }
]}
Here is my Struct:
struct This:Codable {
let type: String?
let name: String?
let crs: CRS
let features: [Features]
struct CRS: Codable {
let type: String?
let properties: CRSProperties
struct CRSProperties: Codable {
let name: String?
enum CodingKeys: String, CodingKey {
case name
}
}
enum CodingKeys: String, CodingKey {
case type
case properties
}
}
struct Features: Codable {
let type: String?
let properties: FeaturesProperties
struct FeaturesProperties: Codable {
let osmId: String?
let name: String?
let highway: String?
let otherTags: String?
let geo: FeaturesPropertiesGeometry?
struct FeaturesPropertiesGeometry: Codable {
let type: String
let coordinates: [Double]
enum CodingKeys: String, CodingKey {
case type
case coordinates
}
}
enum CodingKeys: String, CodingKey {
case osmId = "osm_id"
case name
case highway
case otherTags = "other_tags"
case geo = "geometry"
}
}
enum CodingKeys: String, CodingKey {
case type
case properties
}
}
}
Then here is what I use to decode the JSON
guard let asset = NSDataAsset(name: "NN") else {
print("NN JSON not here")
return
}
do {
let deco = JSONDecoder()
this = try deco.decode(This.self, from: asset.data)
}catch {
print("Error: \(error)")
}
My problem is that I dont get the geometry data into "this: This". If I print every line then from "this" then the result for "geo" is always nil.
This is a printed line.
"Features(type: Optional("Feature"), properties: mokkingaroud.This.Features.FeaturesProperties(osmId: Optional("10587816"), name: Optional("YX Evje"), highway: nil, otherTags: Optional("\"amenity\"=>\"fuel\",\"branch\"=>\"Evje\",\"brand\"=>\"YX\",\"email\"=>\"evje#st.yx.no\",\"fuel:adblue\"=>\"yes\",\"fuel:diesel\"=>\"yes\",\"fuel:HGV_diesel\"=>\"yes\",\"fuel:octane_95\"=>\"yes\",\"fuel:taxfree_diesel\"=>\"yes\",\"hgv\"=>\"yes\",\"phone\"=>\"+47 37 92 95 60\",\"ref:yx\"=>\"561\""), geo: nil))"
Any suggestions please.
Jonas
Because coordinates is not a String I'd use:
struct This:Codable {
let name, type: String?
let features: [Features]
}
struct Features: Codable {
let type: String?
let properties: [Properties]
let geometry: [Geometry]
}
struct Properties:Codable {
let name, osm_id, other_tags: String?
}
struct Geometry:Codable {
let type: String?
let coordinates: [Double]
}
Related
I've given an API with dataclass, I want to fetch the dataclass, I tried to search up on internet but coulnd't find the answer, after that I tried to fetch it with my own, but my code doesn't seem to work. any ideas ?
"restricions": {
"restrictionsByNationality": [
{
"type": "Visit Type",
"data": {
"allowsTourists": true,
"allowsBusinessVisit": true
}
},
{
"type": "Covid Test",
"data": {
"pcrRequired": true,
"fastTestRequired": true
}
},
{
"type": "Documents Required",
"data": {
"biometricPassportRequired": true,
"locatorFormRequired": true,
"covidPassportRequired": false
}
}
]
},
if let nationality = data["restrictionsByNationality"] as? [String: Any]{
nationality = DataClass(from: nationality)
}
struct RestrictionsByNationality: Codable {
let type: String
let data: DataClass
}
// MARK: - DataClass
struct DataClass: Codable {
let allowsTourists,
allowsBusinessVisit, pcrRequired, fastTestRequired: Bool?
let biometricPassportRequired, locatorFormRequired, covidPassportRequired: Bool?
}
}
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 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.
I'm trying to create a struct to model the following bit of JSON, where the high level properties ("Blue Team" and "Green Team") don't have specified keys.
{
"Teams": [
{
"Blue Team": {
"motto": "We're the best",
"players": [
{
"name": "Bob",
"skill": "jumping really high",
"birthday": 1546326611,
},
{
"name": "Julie",
"skill": "really strong",
"birthday": 1546413133,
},
{
"name": "Kirsten",
"skill": "smarty pants",
"birthday": 1546499716,
}
]
},
"Green Team": {... // same structure as above }
}
]
}
I believe I'm close, but I'm not sure how to represent the Blue Team and Red Team. This is what I have so far:
struct AllTeams: Codable {
let Teams: [String : Team]
struct Team: Codable {
//let <property>: ???
}
struct ???: Codable {
let motto: String
let players: [Player]
}
struct Player: Codable {
let name: String
let skill: String
let birthday: Int // will need to convert this
}
}
I suppose you want a [String: Team] in your AllTeams struct?
You can do this:
struct AllTeams: Decodable {
let teams: [String: Team]
enum CodingKeys: String, CodingKey {
case teams = "Teams"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
teams = (try container.decode([[String: Team]].self, forKey: .teams))[0]
}
}
struct Team: Codable {
let motto: String
let players: [Player]
}
struct Player: Codable {
let name, skill: String
let birthday: Date
}
Decoding:
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
let teams = try! decoder.decode(AllTeams.self, from: json)
print(teams.teams["Blue Team"].motto)
Correct json ( as your json is in-complete and contains wrong , at end of birthday keys )
{
"Teams": [{
"Blue Team": {
"motto": "We're the best",
"players": [{
"name": "Bob",
"skill": "jumping really high",
"birthday": 1546326611
},
{
"name": "Julie",
"skill": "really strong",
"birthday": 1546413133
},
{
"name": "Kirsten",
"skill": "smarty pants",
"birthday": 1546499716
}
]
},
"Green Team": {
"motto": "We're the best",
"players": [{
"name": "Bob",
"skill": "jumping really high",
"birthday": 1546326611
},
{
"name": "Julie",
"skill": "really strong",
"birthday": 1546413133
},
{
"name": "Kirsten",
"skill": "smarty pants",
"birthday": 1546499716
}
]
}
}]
}
for 2 keys
struct Root: Codable {
let teams: [Team]
enum CodingKeys: String, CodingKey {
case teams = "Teams"
}
}
struct Team: Codable {
let blueTeam, greenTeam: BlueTeamClass
enum CodingKeys: String, CodingKey {
case blueTeam = "Blue Team"
case greenTeam = "Green Team"
}
}
struct BlueTeamClass: Codable {
let motto: String
let players: [Player]
}
struct Player: Codable {
let name, skill: String
let birthday: Int
}
for dynamic keys
struct Root: Codable {
let teams: [[String:Item]]
enum CodingKeys: String, CodingKey {
case teams = "Teams"
}
}
struct Item: Codable {
let motto: String
let players: [Player]
}
struct Player: Codable {
let name, skill: String
let birthday: Int
}
Decode
do {
let res = try JSONDecoder().decode(Root.self,from:data)
print(res)
}
catch {
print(error)
}
You are indeed pretty close.
As you want to decode the teams as dictionary change the structs to
struct AllTeams: Codable {
let Teams: [[String : Team]]
struct Team: Codable {
let motto: String
let players: [Player]
}
struct Player: Codable {
let name: String
let skill: String
let birthday: Date
}
}
and decode
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
let result = try decoder.decode(AllTeams.self, from: data)
The birthday integer is decoded as Date
For a more sophisticated solution to include the team keys in the Team struct with custom CodingKeys take a look at this answer
Note :
You are encouraged to conform to the naming convention and add CodingKeys to map the uppercased keys to lowercased struct members
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