I have the following JSON...
{
"id": "1000035148",
"petId": "3",
"ownerId": "1000",
"locationId": null,
"status": "Active",
“services”: [
{
"id": "5004",
“data”: 1,
“data1”: 0,
“data2": 63,
“data3": 0
}
]
}
And I'm only trying to return the following objects...
"id": "1000035148",
"petId": "3",
"ownerId": "1000",
"locationId": null,
"status": "Active"
How can I achieve this with the following code?
session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in
if let data = data {
do {
let jsonData = try JSONSerialization.jsonObject(with: data)
if let dictionary = jsonData as? [String: Any] {
if let nestedDictionary = dictionary["status"] as? [String: Any] {
for (key, value) in nestedDictionary {
print("Key: \(key), Value: \(value)")
}
}
}
print(jsonData)
} catch {
print("Error fetching data from API: \(error.localizedDescription)")
}
}
When I try to parse using the nestedDictionary = dictionary I get an error and it skips over the line. I'm confused on how to get just the key value pairs I want from the response.
Forget JSONSerialization and use Decodable with JSONDecoder:
struct DataModel: Decodable {
let id: String
let pedId: String?
let ownerId: String?
let locationId: String?
let status: String
}
do {
let dataModel = try JSONDecoder().decode(DataModel.self, from: data)
print("Status: \(dataModel.status)")
} catch ...
If you want to use JSONSerialization, note that status is not a dictionary, it's a String:
if let dictionary = jsonData as? [String: Any] {
if let status = dictionary["status"] as? String {
print("Status: \(status)")
}
}
Related
There is an API that supplies JSON data that I would like to use. I've given a summary of the JSON below. At the top level, the key to each record is a unique ID that matches the ID in the record itself. These keys are integers in quotes (starting at 1, unsorted and probably not contiguous).
Reading the JSON isn't a problem. What is the Codable "Response" struct required to receive the data?
if let response = try? JSONDecoder().decode(Response.self, from: data)
The JSON
{
"2546": {
"id": "2546",
"title": "Divis and the Black Mountain"
},
"1": {
"id": "1",
"title": "A la Ronde"
},
"2": {
"id": "2",
"title": "Aberconwy House"
}
}
I had this once also, looks like whoever created this endpoint doesn't really understand how JSON works...
try this out and then just return response.values so you have a list of items
struct Item: Codable {
let id, title: String
}
typealias Response = [String: Item]
Use a more dynamic version of CodingKey. You can read more about it here: https://benscheirman.com/2017/06/swift-json/
Check the section "Dynamic Coding Keys"
The Codable type struct Response should be,
struct Response: Decodable {
let id: String
let title: String
}
Now, parse the json data using [String:Response] instead of just Response like so,
do {
let response = try JSONDecoder().decode([String:Response].self, from: data)
print(response) //["1": Response(id: "1", title: "A la Ronde"), "2546": Response(id: "2546", title: "Divis and the Black Mountain"), "2": Response(id: "2", title: "Aberconwy House")]
} catch {
print(error)
}
You should implement a custom CodingKey, something like that:
struct MyResponse {
struct MyResponseItemKey: CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int? { return nil }
init?(intValue: Int) { return nil }
static let id = MyResponseItemKey(stringValue: "id")!
static let title = MyResponseItemKey(stringValue: "title")!
}
struct MyResponseItem {
let id: String
let subItem: MyResponseSubItem
}
struct MyResponseSubItem {
let id: String
let title: String
}
let responseItems: [MyResponseItem]
}
Not sure if the key of each item and the value of id are always equal, that's why there are 2 IDs in MyResponse.
And, of course, MyResponse should conform to Codable:
extension MyResponse: Codable {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: MyResponseItemKey.self)
responseItems = try container.allKeys.map { key in
let containerForKey = try container.nestedContainer(keyedBy: MyResponseItemKey.self, forKey: key)
let id = try containerForKey.decode(String.self, forKey: .id)
let title = try containerForKey.decode(String.self, forKey: .title)
return MyResponseItem(id: key.stringValue, subItem: MyResponseSubItem(id: id, title: title))
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: MyResponseItemKey.self)
for responseItem in responseItems {
if let key = MyResponseItemKey(stringValue: responseItem.id) {
var subItemContainer = container.nestedContainer(keyedBy: MyResponseItemKey.self, forKey: key)
try subItemContainer.encode(responseItem.subItem.id, forKey: .id)
try subItemContainer.encode(responseItem.subItem.title, forKey: .title)
}
}
}
}
This is how you can use MyResponse:
let jsonString = """
{
"2546": {
"id": "2546",
"title": "Divis and the Black Mountain"
},
"1": {
"id": "1",
"title": "A la Ronde"
},
"2": {
"id": "2",
"title": "Aberconwy House"
}
}
"""
if let dataForJSON = jsonString.data(using: .utf8),
let jsonDecoded = try? JSONDecoder().decode(MyResponse.self, from: dataForJSON) {
print(jsonDecoded.responseItems.first ?? "")
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
if let dataFromJSON = try? encoder.encode(jsonDecoded) {
let jsonEncoded = String(data: dataFromJSON, encoding: .utf8)
print(jsonEncoded ?? "")
}
}
{
"AAPL" : {
"quote": {...},
"news": [...],
"chart": [...]
},
"FB" : {
"quote": {...},
"news": [...],
"chart": [...]
},
}
How would you decode this in swift. The stocks change but the underlying quote, news, and chart stay the same. Also to mention this json of stocks could be 500 long with unknown sorting order.
For the information in quote it would look like:
{
"calculationPrice": "tops",
"open": 154,
ect...
}
inside news:
[
{
"datetime": 1545215400000,
"headline": "Voice Search Technology Creates A New Paradigm For
Marketers",
ect...
}
]
Inside charts:
[
{
"date": "2017-04-03",
"open": 143.1192,
ect...
}
]
What I have been trying is something along the lines of this as an example...
Json Response:
{
"kolsh" : {
"description" : "First only brewed in Köln, Germany, now many American brewpubs..."
},
"stout" : {
"description" : "As mysterious as they look, stouts are typically dark brown to pitch black in color..."
}
}
Struct/Model for codable:
struct BeerStyles : Codable {
struct BeerStyleKey : CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int? { return nil }
init?(intValue: Int) { return nil }
static let description = BeerStyleKey(stringValue: "description")!
}
struct BeerStyle : Codable {
let name: String
let description: String
}
let beerStyles : [BeerStyle]
}
Decoder:
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: BeerStyleKey.self)
var styles: [BeerStyle] = []
for key in container.allKeys {
let nested = try container.nestedContainer(keyedBy: BeerStyleKey.self,
forKey: key)
let description = try nested.decode(String.self,
forKey: .description)
styles.append(BeerStyle(name: key.stringValue,
description: description))
}
self.beerStyles = styles
}
This example is from https://benscheirman.com/2017/06/swift-json/ and I'm trying to apply it to my json structure.
Try this code ...:)
Alamofire.request("", method: .get, encoding: JSONEncoding.default) .responseJSON { response in
if response.result.isSuccess{
let json = response.result.value! as? [String : Any] ?? [:]
for (key, value) in json {
//here key will be your apple , fb
let valueofkey = value as? [String:Any] ?? [:]
let quote = valueofkey["quote"] as? [String:Any] ?? [:]
let news = valueofkey["news"] as? [Any] ?? []
let chart = valueofkey["chart"] as? [Any] ?? []
}
}
}
I hope it will work for you ... :)
If the contents of quote, news and chart have same type, i.e. assuming that quote is of type [String:String] and news and chart are of type [String], you can use Codable as well.
Example:
With the below model,
struct Model: Decodable {
let quote: [String:String]
let news: [String]
let chart: [ String]
}
Now, you can parse the JSON like so,
do {
let response = try JSONDecoder().decode([String:Model].self, from: data)
print(response)
} catch {
print(error)
}
How to access JSON using Codable. this is my sample json.
{
"status": "success",
"message": "Data received successfully",
"course": {
"id": 1,
"description": "something",
"name": "ielts",
"attachments": [
{
"id": 809,
"attachment": "https:--",
"file_name": "syllabus.pdf",
"description": "course",
},
{
"id": 809,
"attachment": "https:--",
"file_name": "syllabus.pdf",
"description": "course",
}]
"upcased_name": "IELTS"
}
}
This is my code.
struct ResponseObject: Codable {
let course: [Course]
}
struct Course: Codable {
let id: Int
let name: String
let description: String
let attachments: [Attachments]
}
struct Attachments: Codable {
let id: Int
let attachment: String
let file_name: String
let description: String
let about: String
}
var course: [Course] = []
This is my api call.
func fetchUserData() {
let headers: HTTPHeaders = [
"Authorization": "Token token="+UserDefaults.standard.string(forKey: "auth_token")!,
"Accept": "application/json"
]
let params = ["course_id" : "1"] as [String : AnyObject]
self.showSpinner("Loading...", "Please wait!!")
DispatchQueue.global(qos: .background).async {
AF.request(SMAConstants.courses_get_course_details , parameters: params, headers:headers ).responseDecodable(of: ResponseObject.self, decoder: self.decoder) { response in
DispatchQueue.main.async {
self.hideSpinner()
guard let value = response.value else {
print(response.error ?? "Unknown error")
return
}
self.course = value.course
}
}
}
}
}
I am getting following error.
responseSerializationFailed(reason:
Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error:
Swift.DecodingError.typeMismatch(Swift.Array,
Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue:
"course", intValue: nil)], debugDescription: "Expected to decode
Array but found a dictionary instead.", underlyingError: nil))))
Your model object does not match the JSON structure. Try this instead:
struct ResponseObject: Codable {
let status, message: String
let course: Course
}
struct Course: Codable {
let id: Int
let courseDescription, name: String
let attachments: [Attachment]
let upcasedName: String
enum CodingKeys: String, CodingKey {
case id
case courseDescription = "description"
case name, attachments
case upcasedName = "upcased_name"
}
}
struct Attachment: Codable {
let id: Int
let attachment, fileName, attachmentDescription: String
enum CodingKeys: String, CodingKey {
case id, attachment
case fileName = "file_name"
case attachmentDescription = "description"
}
}
and to download and parse this with plain Swift and Foundation, use code like this:
let url = URL(string: SMAConstants.courses_get_course_details)!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print(error)
return
}
if let data = data {
do {
let response = try JSONDecoder().decode(ResponseObject.self, from: data)
// access your data here
} catch {
print(error)
}
}
}
task.resume()
I have an issue with loading JSON results within swift (php connection).
I can retrieve JSON data but it will not let me assign it to a variable.
it always assigns the results as Optional.
The JSON Data:
{
"country": [{
"id": 1,
"name": "Australia",
"code": 61
}, {
"id": 2,
"name": "New Zealand",
"code": 64
}]
}
The xCode Output:
["country": <__NSArrayI 0x60000002da20>(
{
code = 61;
id = 1;
name = Australia;
},
{
code = 64;
id = 2;
name = "New Zealand";
}
)
]
Country Name: Optional(Australia)
Country Name: Optional(New Zealand)
The .swift file:
//function did_load
override func viewDidLoad() {
super.viewDidLoad()
//created RequestURL
let requestURL = URL(string: get_codes)
//creating NSMutable
let request = NSMutableURLRequest(url: requestURL!)
//setting the method to GET
request.httpMethod = "GET"
//create a task to get results
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil{
print("error is \(String(describing: error))")
return;
}
//lets parse the response
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: Any]
print(json)
if let countries = json["country"] as? [[String: AnyObject]] {
for country in countries {
print("Country Name: \(String(describing: country["name"]))")
print("Country Code: \(String(describing: country["code"]))")
if let couname = country["name"] as? [AnyObject] {
print(couname)
}
if let coucode = country["code"] as? [AnyObject] {
print(coucode)
}
}
}
} catch {
print("Error Serializing JSON: \(error)")
}
}
//executing the task
task.resume()
}
You need to unwrap the optional before you try to use it via string interpolation. The safest way to do that is via optional binding:
Please use below code, which will work for you.
if let countries = json["country"] as? [[String: AnyObject]] {
for country in countries {
print("Country Name: \(country["name"] as! String)")
print("Country Code: \(country["code"] as! String)")
if let couname = country["name"] as? String {
print(couname)
}
if let coucode = country["code"] as? Int {
print(coucode)
}
}
}
I'm trying to create an array of dictionaries from JSON response.
Here is the code.
_ = postView.textView.rx.text
.subscribe(onNext: {[unowned self] _ in
let client = Alamofire.SessionManager.default
_ = client.request(Router.getFriends())
.rx_responseJSON()
.subscribe(onNext: { [weak self] data in
var names = [String]()
do {
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any], //'var' declarations with multiple variables cannot have explicit getters/setters
let friends = json["user"] as? [[String: Any]] {
for friend in friends {
if let name = friend["first_name"] as? String {
names.append(name)
}
}
}
} catch {
print("Error deserializing JSON: \(error)")
}
print(names)
}, onError: { (error) -> Void in
debugPrint("Error: \(error)")
})
})
This is the error I'm getting
'var' declarations with multiple variables cannot have explicit
getters/setters
This is the JSON response,
{
"user": [
{
"id": 2,
"first_name": "Knysys",
"photo": "https://graph.facebook.com/437334666655912/picture/?type=large",
"last_seen_event": null,
"blocked": false
},
{
"id": 3,
"first_name": "ATester",
"photo": "https://graph.facebook.com/379988632393252/picture/?type=large",
"last_seen_event": 7,
"blocked": false
}
]
}
The desired output is this,,
var friends = [
[
"firstName": "SmartApps",
"photo": "https://graph.facebook.com/1248984075179327/picture/?type=large"
],
[
"firstName": "Knysys",
"photo": "https://graph.facebook.com/437334666655912/picture/?type=large"
],
[
"firstName": "ATester",
"photo": "https://graph.facebook.com/379988632393252/picture/?type=large"
]
]
Thanks in advance!
You forgot the if in the line let json = ...
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let friends = json["user"] as? [[String: Any]] {
for friend in friends {
if let name = friend["first_name"] as? String {
names.append(name)
}
}
}
} catch {
print("Error deserializing JSON: \(error)")
}
Here is the code that worked,
let client = Alamofire.SessionManager.default
_ = client.request(Router.getFriends())
.rx_responseJSON()
.subscribe(onNext: { [weak self] data in
self?.friends.removeAll()
let json = data as? [String: Any]
let friends = json?["user"] as! [[String: Any]]
for i in 0 ..< friends.count{
let firstName: String = (friends[i]["first_name"] as! NSString) as String
let photo: String = (friends[i]["photo"] as! NSString) as String
let dict = [
"firstName" : firstName,
"photo" : photo
]
self?.friends.append(dict)
}
self?.friendTableView.reloadData()
self?.friendTableView.sizeToFit()
}, onError: { (error) -> Void in
debugPrint("Error retrieving friends: \(error)")
})