There is a code:

let adress = "http://MyServ/WEB2/odata/standard.odata/Catalog_Klient?$format=json" guard let url = URL(string: adress) else {return} let session = URLSession.shared session.dataTask(with: url) { (data, response, error) in if let response = response { print(response) } guard let data = data else { return} print(data) do { let jsonStr = try JSONSerialization.jsonObject(with: data, options: []) print(jsonStr) } catch{ print(error) } }.resume() 

We have this JSON answer, i.e. my constant "jsonStr":

 { "odata.metadata": "http://MyServ/WEB2/odata/standard.odata/$metadata#Catalog_Klient", "value": [{ "Ref_Key": "c9ca0efd-39a9-11e9-9422-0cc47a448b68", "DataVersion": "AAAAAQAAAAA=", "DeletionMark": false, "Code": "000000001", "Description": "TEST", "Predefined": false, "PredefinedDataName": "" },{ "Ref_Key": "1413903c-39aa-11e9-9422-0cc47a448b68", "DataVersion": "AAAAAgAAAAA=", "DeletionMark": false, "Code": "000000002", "Description": "TEST2", "Predefined": false, "PredefinedDataName": "" }]} 

How to get a table or an array of the form:

1) 000000001 | TEST |

2) 000000002 | TEST2 |

    1 answer 1

    To parse the JSON from the received data, create the structures:

    • ResponseItem - will store the elements of the array:
     struct ResponseItem { var code: String var description: String } 
    • Response - will store the entire server response:
     struct Response { var value: [ResponseItem] } 

    These structures must implement the Decodable protocol. With Response everything is simple, since the answer contains value with a small letter:

     extension Response: Decodable {} 

    With ResponseItem little more complicated, since the server’s response contains keys from a capital letter, while in Swift it is customary to call variables with a small letter. It is necessary to tell the compiler what value to write in which variable when parsing:

     extension ResponseItem: Decodable { enum CodingKeys: String, CodingKey { case code = "Code" case description = "Description" } } 

    Now we use the created structures and parse the answer using JSONDecoder :

     let decoded = try? JSONDecoder().decode(Response.self, from: data) 

    To check, you can display the result in the console:

     print(decoded)